I am not sure about a good way to initialize a shared_ptr that is a member of a class. Can you tell me, whether the way that I choose in C::foo() is fine, or is there a better solution?
class A
{
public:
A();
};
class B
{
public:
B(A* pa);
};
class C
{
boost::shared_ptr<A> mA;
boost::shared_ptr<B> mB;
void foo();
};
void C::foo()
{
A* pa = new A;
mA = boost::shared_ptr<A>(pa);
B* pB = new B(pa);
mB = boost::shared_ptr<B>(pb);
}
Your code is quite correct (it works), but you can use the initialization list, like this:
Which is even more correct and as safe.
If, for whatever reason,
new Aornew Bthrows, you’ll have no leak.If
new Athrows, then no memory is allocated, and the exception aborts your constructor as well. Nothing was constructed.If
new Bthrows, and the exception will still abort your constructor:mAwill be destructed properly.Of course, since an instance of
Brequires a pointer to an instance ofA, the declaration order of the members matters.The member declaration order is correct in your example, but if it was reversed, then your compiler would probably complain about
mBbeeing initialized beforemAand the instantiation ofmBwould likely fail (sincemAwould not be constructed yet, thus callingmA.get()invokes undefined behavior).I would also suggest that you use a
shared_ptr<A>instead of aA*as a parameter for yourBconstructor (if it makes senses and if you can accept the little overhead). It would probably be safer.Perhaps it is guaranteed that an instance of
Bcannot live without an instance ofAand then my advice doesn’t apply, but we’re lacking of context here to give a definitive advice regarding this.