When to Use Smart Pointers in C++ – Guide

c++c++11pointerssmart-pointers

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?

Best Answer

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?