Just wondering what you think is the best practice regarding vectors in C++.
If I have a class containing a vector member variable. When should this vector be declared a
Deleting all elements in a vector manually is an anti-pattern and violates the RAII idiom in C++. So if you have to store pointers to objects in a vector
, better use a 'smart pointer' (for example boost::shared_ptr
) to facilitate resource destructions. boost::shared_ptr
for example calls delete
automatically when the last reference to an object is destroyed.
There is also no need to allocate MyClass::my_vector
using new
. A simple solution would be:
class MyClass {
std::vector m_vector;
};
Assuming whatever
is a smart pointer type, there is no extra work to be done. That's it, all resources are automatically destroyed when the lifetime of a MyClass
instance ends.
In many cases you can even use a plain std::vector
- that's when the objects in the vector are safe to copy.