C ++: replace source pointers with generic and weak ptr

My program has a design problem. I need to manage Nodes objects that are part of the root ChainDescriptor.

It basically looks like this:

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;
};

The ChainDescriptor class owns all nodes and is responsible for their removal. But these classes should now be used in another program, a graphical interface with the ability to cancel / redo, with the problem of "ownership". Before modifying the existing code in depth, I consider various solutions:

  • using shared_ptrand relevantlist<shared_ptr<...> >
  • using weak_ptrand appropriatelist<weak_ptr<...> >

In the above example, I really don't know where to use shared_ptrand correctly weak_ptr.

Any suggestion?

+4
4

shared_ptr m_childs weak_ptr m_parent.

, , Node - . - , .

shared_ptr ChainDescriptor Node. ( ).

, .

+3

shared_ptr , weak_ptr .

, , ChainDescriptor shared_ptr ( ), Node weak_ptr m_parent ( ) shared_ptr m_childs ( ).

+3

node (.. ), .

, . , , ( ), ( ).

, ChainDescriptor .

+1

- . , , . " " - ChainDescriptor, . ( Node Node ChainDescriptor.) , , ; , .

, , , . , std::shared_ptr , 1) Node "" a ChainDescriptor, Node, 2) , , DAG (, , ). , , shared_ptr . , ChainDescriptor shared_ptr.

(FWIW: I used a reference count for nodes in a parse tree that I wrote many years ago, and different instances can share subtrees. But I developed it from start using reference counted pointers. And because of how the tree was built I was sure that there could be cycles.)

+1
source

All Articles