Imagine a class C that has a member variable m_MyList of type std::vector in which I want to store objects of type MyClass. C has two functions that add or remove objects in m_MyList.
m_MyList should also be made accessible for consumers of C as they need to read the collection of MyClass objects. The external reader of the collection will have no means to change the collection, thus the MyClass objects are owned only by C.
Now my question: In C++11 style, what is the best T to store in the vector? The possibilities seem to be:
std::vector<MyClass>std::vector<MyClass*>std::vector<unique_ptr<MyClass>>, usingstd:moveto push theunique_ptrinto thevector
If the
MyClassobjects are owned byC, then the best option would be the simplest:The only reason I could see for using
std::unique_ptrshere is if you need to keep pointers to a base class for polymorphism. In this case the unique_ptrs serve the purpose of releasing resources upon destruction of the vector. But then theCinterface should not transfer ownership to the clients.