J
Jess
Hello,
I have a program that stores dynamically created objects into a
vector.
#include<iostream>
#include<vector>
using namespace std;
class A{
public:
A(){cout << "A()" << endl;}
~A(){cout << "~A()" << endl;}
};
int main(){
vector<A> v;
v.push_back(*new A);
v.push_back(*new A);
v.push_back(*new A);
return 0;
}
I output the messages for A() and ~A() to see what's been constructed/
destructed. Here is the output,
A()
A()
~A()
A()
~A()
~A()
~A()
~A()
~A()
This is quite surprising, as I expected the output to be
A()
A()
A()
~A()
~A()
~A()
because the program makes three new A objects and pushed them onto the
vector, hence I think there should be three consecutive A(), without
a "~A()" between the 2nd and 3rd "A()". When the vector is destroyed,
I think all its stored objects are destroyed, hence there should be
three "~A()". What's my mistake?
I also tried to store the pointers into the vector:
#include<iostream>
#include<vector>
using namespace std;
class A{
public:
A(){cout << "A()" << endl;}
~A(){cout << "~A()" << endl;}
};
int main(){
vector<A*> v;
v.push_back(new A);
v.push_back(new A);
v.push_back(new A);
return 0;
}
Now the output is only
A()
A()
A()
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?
Finally, can someone please tell me what's the correct way to store
dynamically created objects into a vector?
Thanks,
Jess
I have a program that stores dynamically created objects into a
vector.
#include<iostream>
#include<vector>
using namespace std;
class A{
public:
A(){cout << "A()" << endl;}
~A(){cout << "~A()" << endl;}
};
int main(){
vector<A> v;
v.push_back(*new A);
v.push_back(*new A);
v.push_back(*new A);
return 0;
}
I output the messages for A() and ~A() to see what's been constructed/
destructed. Here is the output,
A()
A()
~A()
A()
~A()
~A()
~A()
~A()
~A()
This is quite surprising, as I expected the output to be
A()
A()
A()
~A()
~A()
~A()
because the program makes three new A objects and pushed them onto the
vector, hence I think there should be three consecutive A(), without
a "~A()" between the 2nd and 3rd "A()". When the vector is destroyed,
I think all its stored objects are destroyed, hence there should be
three "~A()". What's my mistake?
I also tried to store the pointers into the vector:
#include<iostream>
#include<vector>
using namespace std;
class A{
public:
A(){cout << "A()" << endl;}
~A(){cout << "~A()" << endl;}
};
int main(){
vector<A*> v;
v.push_back(new A);
v.push_back(new A);
v.push_back(new A);
return 0;
}
Now the output is only
A()
A()
A()
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?
Finally, can someone please tell me what's the correct way to store
dynamically created objects into a vector?
Thanks,
Jess