Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw vs Unique pointers in the list

Tags:

c++

unique-ptr

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);
like image 218
Alexey Teplyakov Avatar asked Oct 03 '22 12:10

Alexey Teplyakov


1 Answers

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.

like image 107
TemplateRex Avatar answered Oct 12 '22 12:10

TemplateRex