I love declaring variables on the stack, especially when using the standard container. Each time you avoid a new, you avoid a potential memory leak.
I also like using polymorphism, ie class hierarchies with virtual functions. However, it seems these features are a bit incompatible: you can’t do:
std::vector<BaseType> vec;
vec.push_back(DerivedType())
or at least it seems you would lose the polymorphic nature of the object you push in.
So, is there any way to reconcile stack-based memory management and the use of virtual functions?
Well the obvious answer:
But probably not what you intended.
dandvecbetter die at the same time; ifvecoutlivesdyou’ve got a bad pointer.I think what you really want is something like Boost pointer containers:
So you don’t have to worry about leaks. The pointer containers were made specifically for the task of easing use and storage of polymorphic objects.