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?
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With