我在我的程序中遇到了一個設計問題。 我必須管理作爲根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)? –