简体   繁体   中英

Deleting an object in boost wrapper in C++

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.

  1. Is that an automatic behavior in this case ? or do I need to write something for it, give this list has references ?
  2. 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.

Is that an automatic behavior in this case?

No. Storing a reference_wrapper is equivalent to storing a raw pointer. In fact, there's no good reason for storing reference_wrapper rather than polygonType* here.

If I want them to not be deleted what do I need to do?

Store pointers (or reference_wrapper , if you insist on obfuscation). It would probably be more efficient to use vector rather than list :

std::vector<polygonType*> children;

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 I want them deleted what do I need to do ?

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:

std::list<polygonType> children;

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 than list if you're storing pointers rather than objects:

std::vector<std::unique_ptr<polygonType>> children;

If you're stuck with a pre-2011 library, you might use boost::shared_ptr rather than std::unique_ptr ; or perhaps a Boost pointer container .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM