Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

c++ - Two calls to destructor

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your output doesn't account for the Test's copy constructor, which std::vector is apt to use.

The Test object you see get created is the temporary passed to push_back(), not the one actually in the vector.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...