Is the following a good way of describing ownership intent (without using shared_ptr?)
class Z { };
class A
{
unique_ptr<Z> m_z; //want to say 'I own Z'
};
class B
{
B(A & a)
{
m_z = a._z.get();
}
Z* m_z; //want to say 'I do not own Z, just a ref...'
}
Also, B._z can be dangling. Is there a way to rectify the problem without resorting to shared_ptr and weak_ptr?
unique_ptr is Ok for ownership. If raw pointers to that object are still given out and stored elsewhere (and so it is technically shared) then that may confuse readers of your code.
If you do not want to use shared_ptr and do not want to have dangling pointers then observer pattern might help you out. Using it you can ensure that class B instance gets signaled when its _z gets destroyed. That might be is a bit more expensive than shared_ptr in A and weak_ptr in B. For thread safe example try … Boost.Signals2.
I agree that weak_ptr usage looks ugly, but the observer thing will also add some bloat to code.