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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With