!! MEMORY LEAK ALERT !!
Your code, as it is, is leaking.
Any exception thrown inside the copy constructor ( std::bad_alloc ?) std::bad_alloc cause a memory leak since the memory passed in vector will never be cleared (the destructor will not be called since the object was never built in the first place).
You could, of course, add the required try/catch , although I warn you that the code will become awkward soon (you need a few).
This is a direct result of a violation of resource management rule 1 :
An object must manage a resource of not more than one , in which case it should not do anything else.
This means that if your object is a business object (with internal application logic), it should not directly access resource management, but instead use existing managers.
In your case, you have two solutions:
- Recommended: since you are not using polymorphism here, do not use pointers.
std::vector<MyStuff> great - If you need polymorphism, but he did not include it in this toy example, use
boost::ptr_vector<MyStuff>
Bonus Point: Two of these are defined by reasonable copy constructors, assignment operators, and destructors, so you don't have to rewrite them yourself.
EDIT:
As @David noted, if you need polymorphism, you cannot use the copy construct and therefore need to:
- a
clone or equivalent - pointers and dynamic memory allocation
boost::ptr_vector provide everything you need for this (with automatic use of the clone method when copying).
source share