using shared pointer in a linked data structure
Basically I'm having trouble understanding exactly how to use
shared_ptr . If I have a class:
GraphNode
{
public:
AddChild(shared_ptr<GraphNode> n)
{
m_Children.push_back(n);
shared_ptr<GraphNode> thisptr(this);
n->m_Parents.push_back(thisptr);
}
DeleteChild(shared_ptr<GraphNode> n);
private:
vector
Zumichu wrote:
GraphNode { public: AddChild(shared_ptr<GraphNode> n) { m_Children.push_back(n); shared_ptr<GraphNode> thisptr(this); n->m_Parents.push_back(thisptr); }
DeleteChild(shared_ptr<GraphNode> n);
private: vector
m_Children; vector m_Parents; };
There are two problems with your code. First, shared_ptr<GraphNode> thisptr(this); is wrong. A shared_ptr cannot be constructed from an arbitrary raw pointer. Change AddChild to: friend void AddChild(shared_ptr<GraphNode> this_, shared_ptr<GraphNode> n) { this_->m_Children.push_back(n); n->m_Parents.push_back(this_); } Second, you will now have a cyclic reference where the child owns its parents and the parent owns its children, and they'll keep each other alive, creating a memory leak. Change m_Parents to vector< weak_ptr<GraphNode> > m_Parents; to prevent that from happening. vector< GraphNode* > m_Parents; combined with your original AddChild is possible, too, if you aren't afraid of parents disappearing without notice.
participants (2)
-
Peter Dimov
-
Zumichu