Re: problems of storing dynamically created objects in a vector
On 2007-06-10, Jess <wdfcj@hotmail.com> wrote:
#include<iostream>
#include<vector>
using namespace std;
class A{
public:
A(){cout << "A()" << endl;}
~A(){cout << "~A()" << endl;}
};
Before going any further, add a logging copy constructor (and a
logging assignment operator for completeness). You are missing a lot
of detail because you are logging all destructions, but not all
constructions. Something like:
A(const A&)
{ cout << "A(const A&)" << endl; }
A& operator=(const A&)
{ cout << "op=(const A&)" << endl; return *this; }
int main(){
vector<A> v;
v.push_back(*new A);
v.push_back(*new A);
v.push_back(*new A);
return 0;
}
Here you are creating three new A objects and pushing a *copy* of each
into the vector. You are then never destroying the original objects.
int main(){
vector<A*> v;
v.push_back(new A);
v.push_back(new A);
v.push_back(new A);
return 0;
}
It seems the three objects are never destroyed. I guess when a vector
is destroyed, if its contents are pointers, then the pointers are
destroyed, but not the pointed objects. Is this correct?
This is correct by the compiler. If you follow this pattern and you
have no other copy of the pointers through which to delete the objects
then you must be sure to manually delete each pointer in the vector
before either removing that pointer from the vector or letting the
vector by destroyed (e.g. by going out of scope).