Recently I've been frequently running into situations where I needed something similar to this data structure.
Restrictions: C++03 standard.
+-----+--------------+ +----+
|node0| NodeDataRef ->-------------->|data|
+-----+--------------+ +----+
+-----+--------------+ ^^ ^
|node1| NodeDataRef ->----------------+| |
+-----+--------------+ | |
+-----+--------------+ | |
|node2| NodeDataRef ->-----------------+ |
+-----+--------------+ |
|
+-----+--------------+ |
|root | RootDataRef ->-------------------+
+-----+--------------+
Node
classes, where each Node
holds NodeDataRef
"reference" (think shared_ptr
) to the same instance of "Data
" (class, structure, whatever - dynamically allocated). Root
" or "master" node/class that holds RootDataRef
reference (this time, think weak_ptr
) to the same "Data
".Node
s are destroyed, data
is also destroyed and RootDataRef
is set to 0
/NULL
. I.e. NodeDataRef
acts like shared_ptr<Data>
and RootDataRef
acts like weak_ptr<Data>
NodeDataRef
s. In this situation all NodeDataRef
s that were pointing to the data are set to NULL
/0
and RootDataRef
is also set to 0
/NULL
.I.e. weak_ptr<Data>
that can force destruction of all linked shared_ptr<Data>
.
Does this pattern/smart pointer type has a name?
As far as I know, no, this is not a typical ownership pattern with a commonly used name.
How can I quickly implement this using either Boost or Qt 4? ("quickly" means without writing a class to maintain list of references)
There is no pre-packaged ownership policy for this use case, because that would defeat the point of shared ownership. If several shared pointers to a given object exist, by definition those shared pointers have to keep that object alive. If I am given a shared pointer, that's a guarantee that the object will exist until I release it.
If you want one master object to be able to command the destruction of the pointed object no matter whether other objects hold a shared pointer to it, then you will have to figure some separate mechanism for letting it command all the holders of a shared pointer to that object to release it.
UPDATE:
Although "hacky" solutions exist to make this work "quickly", I would not recommend you using any of them. This pattern is atypical enough for you to want it to be evident when someone reads your code (including you in a few months from now).
Your intent should be made clear through explicit communication patterns between the master object and the other owners, instead of being hidden somewhere in a wrapper, custom deleter, or whatever else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With