Possible Duplicate:
C++ Vector Pointers to Objects
Does std::list::remove method call destructor of each removed element?
If I have a std::vector defined as:
std::vector<Object*>* myObjects;
And then call:
delete myObjects;
Will the elements in myObjects then also be deleted? Is there any difference using an std::array or any other stl container?
Thanks in advance
No, and here’s why.
Consider these two cases:
If calling
deleteon thevector*s calleddeleteon the pointers they hold, then you’d be in for a heap of trouble (pun intended) because you’d bedeleteing automatic variables with the firstdeletewhich yields undefined behaviour (a bad thing).You have to manually iterate the
vectoranddeletethe pointers yourself when you know they’re dynamically allocated, or better, usestd::unique_ptrand you never need to calldeleteon anything.Also, you probably don’t need a pointer to a
vectorin the first place, but I won’t judge you since I don’t know your situation.As for
std::arrayandstd::vector, you need to know the size of yourstd::arrayat compile time and you can’t resize it at runtime, butvectorhas neither of those restrictions.