I have a class which has an element
std::list<boost::reference_wrapper<polygonType> > m_children;
When an object is created out of this class, i store all the children of that object as reference in this variable. What I wanted to do is, when the destructor of the object is called, I wanted the destructor of the children to be called to.
- Is that an automatic behavior in this case ? or do I need to write something for it, give this list has references ?
- If I want them to not be deleted what do I need to do ? If I want them deleted what do I need to do ?
This basically comes down to some of the design decisions I made and how I want them fixed.
No. Storing a
reference_wrapper
is equivalent to storing a raw pointer. In fact, there's no good reason for storingreference_wrapper
rather thanpolygonType*
here.Store pointers (or
reference_wrapper
, if you insist on obfuscation). It would probably be more efficient to usevector
rather thanlist
:You must be careful that whatever is responsible for destroying the children doesn't leave dangling pointers here. You might consider managing them with shared pointers, and storing weak pointers in the list, to ensure that doesn't happen.
If
polygonType
is a concrete type, then you might store the children directly in the list. In this case,list
may be the better choice, since it will never copy or move the objects it contains:If it's a polymorphic base class, so that you can't store the objects directly, then store smart pointers. Again,
vector
is probably a better choice thanlist
if you're storing pointers rather than objects:If you're stuck with a pre-2011 library, you might use
boost::shared_ptr
rather thanstd::unique_ptr
; or perhaps a Boost pointer container.