Your code is quite correct (it works), but you can use the initialization list, like this:
C::C() :
mA(new A),
mB(new B(mA.get())
{
}
Which is even more correct and as safe.
If, for whatever reason, new A
or new B
throws, you'll have no leak.
If new A
throws, then no memory is allocated, and the exception aborts your constructor as well. Nothing was constructed.
If new B
throws, and the exception will still abort your constructor: mA
will be destructed properly.
Of course, since an instance of B
requires a pointer to an instance of A
, 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 mB
beeing initialized before mA
and the instantiation of mB
would likely fail (since mA
would not be constructed yet, thus calling mA.get()
invokes undefined behavior).
I would also suggest that you use a shared_ptr<A>
instead of a A*
as a parameter for your B
constructor (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 B
cannot live without an instance of A
and then my advice doesn't apply, but we're lacking of context here to give a definitive advice regarding this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…