Raw vs Unique Pointers on the List

Say I have a std :: list of some class T.

What is the best way to manage these elements? Given that only the manager (I mean 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); 
+4
source share
2 answers

If the ownership model in your program is that the list “owns” the elements inside it, the second way (that is, with unique_ptr<T> ) is better. It allows C ++ to manage the resources of your list automatically, which is especially important in situations where the list is declared in the local scope, because you do not need to worry about leaving the scope prematurely.

+1
source

In the words Herb Sutter GotW column :

Indication To select an object, prefer to write make_unique by default and write make_shared when you know that the lifetime of objects will be controlled 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 clause to implement std :: make_unique.

+3
source

Source: https://habr.com/ru/post/1492306/


All Articles