我在程序中遇到了一个设计问题。我需要管理节点对象,这些节点对象是根ChainDescriptor的一部分。
基本上看起来像下面这样:
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
。有什么建议吗?
boost::ptr_list
呢? - Bartek Banachewicz