For the following code:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
struct Test
{
string Str;
Test(const string s) :Str(s)
{
cout<<Str<<" Test() "<<this<<endl;
}
~Test()
{
cout<<Str<<" ~Test() "<<this<<endl;
}
};
struct TestWrapper
{
vector<Test> vObj;
TestWrapper(const string s)
{
cout<<"TestWrapper() "<<this<<endl;
vObj.push_back(s);
}
~TestWrapper()
{
cout<<"~TestWrapper() "<<this<<endl;
}
};
int main ()
{
TestWrapper obj("ABC");
}
This was the output that I got on my MSVC++ compiler:
TestWrapper() 0018F854
ABC Test() 0018F634
ABC ~Test() 0018F634
~TestWrapper() 0018F854
ABC ~Test() 003D8490
Why there are two calls to Test destructor although only one Test object is being created. Is there any temporary object created in between? If yes, why there is no call to its corresponding constructor?
Am I missing something?
Your output doesn’t account for the Test’s copy constructor, which
std::vectoris apt to use.The Test object you see get created is the temporary passed to
push_back(), not the one actually in thevector.