我在我的程序中遇到了一个设计问题。 我必须管理作为根ChainDescriptor一部分的Nodes对象。C++:用共享和弱ptr替换原始指针
基本上它看起来如下:
class ChainDescriptor
{
public:
~ChainDescriptor()
{
//delete the nodes in nodes...
}
void addNode(Node *);
Node * getNode();
const std::list<Node *>& getNodes() const;
std::list<Node *> m_nodes;
};
class Node
{
public:
Node(Node *parent);
void addChild(Node *node);
Node * getChild(const std::string& nodeName);
private:
Node * m_parent;
std::list<Node*> m_childs;
};
的ChainDescriptor类拥有的所有节点,并负责删除它们。 但是这些类现在需要用在另一个程序中,一个具有撤销/重做功能的GUI,以及“所有权”的问题。 修改深度现有的代码之前,我考虑了不同的解决方案:
- 使用
weak_ptr
和各自list<weak_ptr<...> >
在上面的例子中使用shared_ptr
和各自list<shared_ptr<...> >
shared_ptr
和weak_ptr
正确。 有什么建议吗?
[boost :: ptr_list']怎么样(http://www.boost.org/doc/libs /1_55_0/libs/ptr_container/doc/ptr_list.html)? –