class B;
class A
{
public:
A ()
: m_b(new B())
{
}
shared_ptr GimmeB ()
{
return m_b;
}
private:
shared_ptr&l
Your analysis is quite correct, I think. In this situation, I also would return a bare B*
, or even a [const] B&
if the object is guaranteed to never be null.
Having had some time to peruse smart pointers, I arrived at some guidelines which tell me what to do in many cases:
std::unique_ptr
. The caller can assign it to a std::shared_ptr
if it wants.std::shared_ptr
is actually quite rare, and when it makes sense, it is generally obvious: you indicate to the caller that it will prolong the lifetime of the pointed-to object beyond the lifetime of the object which was originally maintaining the resource. Returning shared pointers from factories is no exception: you must do this eg. when you use std::enable_shared_from_this
.std::weak_ptr
, except when you want to make sense of the lock
method. This has some uses, but they are rare. In your example, if the lifetime of the A
object was not deterministic from the caller's point of view, this would have been something to consider.nullptr
value.