Search ProofOfProgress Blog

Monday, February 15, 2016

Ownership of pointers in c++ and borrow boxes

Trying to wrap my head around ownership of pointers in c++. Trying to establish rules to make good software. Here are some ideas. 1. Only one object has ownership of any given object. 2. If an object owns another object, when delete[] is called on the parent, it should be called on the child. 3. If an object does NOT own another object, when we delete[] the parent, the other object referenced from within the parent should not be deleted. 4. Any object should either OWN every object it references, or NOT-OWN every object it references. This is to simplify it. So we know exactly what needs to be done to children when delete[] is called. 5. Don't give out references to stuff you don't own. If a class does NOT own the object, it should not be allowed to give out a reference to it. The object that wants the reference should go to the source. ANALOGY: I can't give library book to stranger. The stranger needs to go to the library to get the book I have. Not the best analogy. Since the book they get from the library would also be the book I have. Because we are talking about reference types, not value types. 6. What about classes that absolutely must own some things, but not others? Classes that need mixed ownership must have a "borrow box" or "sandbox" or whatever you want to call it. It is an object OWNED by the parent, so it can be deleted by the parent when the parent is deleted. HOWEVER, the "borrow box" container never owns anything inside it. So when it is destroyed, none of it's contents are deleted. Again, with the rule of not giving out things you don't own... Borrow boxes should never be passed around. A borrow box should not simply be a wrapper you wrap individual objects in. So that you can pass the wrapper around. That wouldn't solve the problem. It would just add another step. The borrow boxes should be taylored to each and every individual class that needs one. No other classes should know about the borrow boxes. So why even have them then? Is it simply a formality that makes the code easier to read? Is it simply a way to avoid individually flagging ownership? It seems like a good idea. But I need more time to think about it. Is it worth the extra -> jump every time you need to reference it?

No comments:

Post a Comment