Alexey Teplyakov
Alexey Teplyakov

Reputation: 316

Raw vs Unique pointers in the list

Let's say I have std::list of some class T.

What is the best way to manage these elements? Considering that only the manager(I mean - the one owner) can add or remove items from the list.

1)

std::list < T* > myList;

//adding the new element
myList.push_back( new T(..) );

//deleting the one element
...roaming through the list...got it...
delete *iterator;
myList.erase(iterator);

2)

std::list < std::unique_ptr<T> > myList;

//adding the new element
myList.push_back ( std::unique_ptr<T>( new T(..) );

//deleting the one element
...roaming through the list...got it...
myList.erase(iterator);

Upvotes: 5

Views: 3691

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727027

If the ownership model in your program is that the list "owns" the elements inside it, the second way (i.e. with unique_ptr<T>) is better. It lets C++ manage the resources of your list automatically, which is especially important in situations when the list is declared in a local scope, because you do not have to worry about exiting the scope prematurely.

Upvotes: 1

TemplateRex
TemplateRex

Reputation: 70556

In the words of Herb Sutter's GotW column:

Guideline: To allocate an object, prefer to write make_unique by default, and write make_shared when you know the object’s lifetime is going to be managed by using shared_ptrs.

std::list < std::unique_ptr<T> > myList;

//adding the new element
myList.push_back ( std::make_unique<T>(..) );

//deleting the one element
...roaming through the list...got it...
myList.erase(iterator);

You can use Stephan T. Lavavej's accepted C+14 proposal for the std::make_unique implementation.

Upvotes: 3

Related Questions