Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a smart pointer?

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?

like image 462
gliderkite Avatar asked Jul 02 '12 09:07

gliderkite


2 Answers

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?

like image 149
Puppy Avatar answered Nov 08 '22 18:11

Puppy


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_ptrs.

like image 44
rodrigo Avatar answered Nov 08 '22 18:11

rodrigo