Appropriate use of shared_ptr?

Without experience with shared_ptr<> I wonder if the following usage example is suitable, and is it also a good opportunity to return shared_ptr<> user.

I have a diagram that looks like a structure with multiple connections between nodes. During the graph traversal, each node is assigned a value (calculated from connected nodes), and I want the user to easily access the value. All this looks (greatly simplified) as follows:

 class Pool; class Node { public: typedef std::tr1::shared_ptr<Node> Ptr; ... void compute_dependencies() { ... // calls Pool to get a new Node instance dependencies_.push_back(Pool::create_node(...)); ... } // evaluate the current node void evaluate() { /* use dependencies_ */ }; double value() const { if(evaluated) return value_; }; private: std::vector<Node::Ptr> dependencies_; // vector<Node*> better? dbl value_; } // Pool creates and owns all nodes class Pool { public: static const Node::Ptr create_node(...); // create a new node void traverse_and_evaluate(); private: std::vector<Node::Ptr> allnodes; // appropriately sorted to ensure // dependencies are evaluated ... } 

and the user calls:

 Pool pool(); Node::Ptr node1 = Pool::create_node(...); Node::Ptr node2 = Pool::create_node(...); .... pool.traverse_and_evaluate(); // ready to read out the now populated values cout << node1->value() << " " << node2->value() << ... 

This has the advantage that the user has direct access to the nodes he cares about (dependencies are often uninteresting). But I'm not 100% sure, this is a good idea.

Thanks for your input!

Edit: There are no circular dependencies.

+8
c ++ shared-ptr
source share
2 answers

shared_ptr is primarily useful in times when an object does not have a clear owner (or perhaps it needs to outlive its owner), so there is no obvious place to destroy it. shared_ptr essentially becomes the owner, and the object is destroyed when the last shared_ptr to it goes out of scope.

When you have an explicit owner, for example your Pool class, and there is no need for Node objects to go to the Pool listing, then really not so much is needed for shared_ptr , you can just destroy the objects in the owner's destructor.

+10
source share

I like to provide access to other users through weak_ptr, you can build weak_ptr <Node> directly from shared_ptr <Node>.

The user usually retrieves weak_ptr from the pool and then creates shared_ptr <Node> from weak_ptr <Node> .lock ().

This tells the user that they do not have ownership rights, and you should be careful not to maintain the lock for longer than necessary - or at least this is with me :)

+3
source share

All Articles