Reputation: 8928
I have a class like the following:
class node
{
public:
node* parent;
std::list<node*> children;
};
Should I use a smart pointer instead of raw pointers? Why? If yes, what kind of smart pointer?
Upvotes: 8
Views: 1877
Reputation: 147028
Always use a smart pointer wherever you own resources (memory, files etc). Owning them manually is extremely error prone and violates many good practices, like DRY.
Which one to use depends on what ownership semantics you need. unique_ptr
is best for single ownership, and shared_ptr
shared ownership.
As children do not own their parents, a raw parent pointer is fine. However, if the parents own their children, unique_ptr
works best here.
It's also notable that what on earth, a linked list of pointers? That makes no sense. Why not a linked list of values?
Upvotes: 16
Reputation: 154027
Absolutely not. The usual smart pointers don't work with graph-like structures, and should be avoided. In this case, you have a tree, and there's no problem handling all of the deletions (and allocations) from the tree object itself.
Upvotes: -2
Reputation: 98496
It is always a good idea to use smart pointers, but beware of loops of references.
class node
{
public:
std::weak_ptr<node> parent;
std::list< std::shared_ptr<node> > children;
};
That's why there is the weak_ptr
in the first place. Note that they are not so smart to detect the loops, you have to do it manually, and break them by using weak_ptr
s.
Upvotes: 5