【发布时间】:2013-11-27 07:52:34
【问题描述】:
我的程序遇到了设计问题。 我必须管理属于根 ChainDescriptor 的 Nodes 对象。
基本上如下所示:
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,具有“所有权”的问题。 在深入修改现有代码之前,我正在考虑不同的解决方案:
- 使用
shared_ptr和各自的list<shared_ptr<...> > - 使用
weak_ptr和各自的list<weak_ptr<...> >
在上面的例子中,我真的不知道在哪里正确使用shared_ptr和weak_ptr。
有什么建议吗?
【问题讨论】:
标签: c++ memory-management boost shared-ptr weak-ptr