0

我有一个有元素的类 std::list<boost::reference_wrapper<polygonType> > m_children;

当一个对象从这个类中创建出来时,我将该对象的所有子对象作为引用存储在这个变量中。我想做的是,当调用对象的析构函数时,我希望调用孩子的析构函数。

  1. 在这种情况下,这是一种自动行为吗?还是我需要为它写点东西,给这个列表有参考?
  2. 如果我希望它们不被删除,我需要做什么?如果我想删除它们,我需要做什么?

这基本上归结为我做出的一些设计决策以及我希望如何修复它们。

4

1 回答 1

1

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.

于 2013-09-11T15:27:50.053 回答