3

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?

Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
jameszhao00
  • 7,213
  • 15
  • 62
  • 112
  • "without using shared_ptr" -> why don't you want to use shared_ptr + weak_ptr ? – Johannes Schaub - litb Dec 18 '10 at 03:23
  • I'm having trouble with the unpredictability of ref-counting object deletion. I just want to stick with scope/unique pointers for now. – jameszhao00 Dec 18 '10 at 03:26
  • Also, don't know if unique_ptr exhibits this problem, but weak_ptr's equality testing is awkward(/non-existant?). – jameszhao00 Dec 18 '10 at 03:27
  • @Johannes Schaub - litb: With shared pointer you would also implicitly allow copying of the A. Using unique_ptr its not copyable. I am all for this type of question, new devs should learn to use the different type of smart pointer all to often people just fall back and use shared_ptr fo everything without thinking. @jameszhao00: please consider **not** using '_' as the first character in your identifiers. You have managed to avoid the problems in this example but do you know all the rules about '_' at the beginning of an identifier? If not then avoid there usage. – Martin York Dec 18 '10 at 17:43
  • @Martin York: Sorry I'm not familiar with the intricacies associated with '_'. Can you please explain? – jameszhao00 Dec 20 '10 at 14:49
  • @jameszhao00: [what-are-the-rules-about-using-an-underscore-in-a-c-identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797) – Martin York Dec 20 '10 at 16:54

1 Answers1

2

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.

Öö Tiib
  • 10,809
  • 25
  • 44