C ++:用共享和弱ptr替换原始指针 [英] C++: Replace raw pointers with shared and weak ptr

查看:94
本文介绍了C ++:用共享和弱ptr替换原始指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在程序中遇到设计问题. 我必须管理作为根ChainDescriptor一部分的Nodes对象.

I'm facing a design issue in my program. I have to manage Nodes object which are part of a root 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,并且存在所有权"的问题. 在深入修改现有代码之前,我正在考虑不同的解决方案:

The ChainDescriptor class owns all the nodes and is responsible of deleting them. But these classes need now to be used in another program, a GUI with undo/redo capabilities, with the problematic of the "ownership". Before modifying the existing code in depth, I'm considering the different solutions:

  • 使用shared_ptr和相应的list<shared_ptr<...> >
  • 使用weak_ptr和相应的list<weak_ptr<...> >
  • using shared_ptr and respective list<shared_ptr<...> >
  • using weak_ptr and respective list<weak_ptr<...> >

在上面的示例中,我真的不知道在哪里正确使用shared_ptrweak_ptr.

In the example above, I don't really know where to use shared_ptr and weak_ptr properly.

有什么建议吗?

推荐答案

您可以将shared_ptr用于m_childs,将weak_ptr用于m_parent.

You can use shared_ptr for m_childs and weak_ptr for m_parent.

但是,保留指向父级Node的原始指针并且根本不使用任何弱指针可能仍然是合理的.其背后的保护机制是非空父代始终存在的不变性.

However, it might be still reasonable to retain the raw pointer to the parent Node and don't use any weak pointers at all. The safeguarding mechanism behind this is the invariant that non-null parent always exists.

另一个选择是仅在ChainDescriptor中使用shared_ptr并将所有原始指针保留在Node中.这种方法避免了弱指针,并具有清晰的所有权策略(父节点拥有自己的子节点).

Another option is using shared_ptr in ChainDescriptor only and retaining all raw pointers in Node. This approach avoids weak pointers and has a clean ownership policy (parent nodes own their children).

弱指针将帮助您自动管理内存,但是其缺点是模糊的所有权逻辑和性能损失.

Weak pointers will help you to manage the memory automatically, but the backside of this are fuzzy ownership logic and performance penalties.

这篇关于C ++:用共享和弱ptr替换原始指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆