When I use the std container in c++, I find a funny part I cant understand, anybody can help? The second class contain a container of first class, when the second class creat a local object and push it into container, it will die when outside the function, but it still have one worked in the container and there is only one constructor work, but two destructor work, why????
The first class is:
#include <iostream>
using namespace std;
class Test1{
private:
public:
Test1(){
cout << "this is in." << endl;
};
~Test1(){
cout << "this is out." << endl;
};
void thiswork(){
cout << "he is still working" << endl;
}
};
The second class is:
#include "test1.hh"
#include <vector>
using namespace std;
class Test2{
public:
Test2(){
cout << "this is test2 creat." << endl;
};
~Test2(){
cout << "this is test2 die" << endl;
};
void init(){
Test1 first;
test2.push_back(first);
cout << "into vector" << endl;
test2[0].thiswork();
};
void dummy(){
cout << "into dummy" << endl;
test2[0].thiswork();
};
private:
vector<Test1> test2 = {};
};
test code:
#include "test2.hh"
int main(){
Test2 test = Test2();
test.init();
test.dummy();
return 0;
}
surprisingly result:
this is test2 creat.
this is in.
into vector
he is still working
this is out.
into dummy
he is still working
this is test2 die
this is out.