本文介绍了两次调用destructor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

 #include< iostream> 
#include< vector>
#include< string>
using namespace std;

struct Test
{

string Str;
Test(const string s):Str(s)
{
cout<<<<Test()<<<
}
〜Test()
{
cout<<<<
}
};

struct TestWrapper
{
vector< Test> vObj;
TestWrapper(const string s)
{
cout<<TestWrapper()<<<< endl;
vObj.push_back(s);
}

〜TestWrapper()
{
cout<〜TestWrapper()<<<< endl;
}
};

int main()
{
TestWrapper obj(ABC);
}

这是我在MSVC ++编译器上得到的输出:



TestWrapper()0018F854

ABC测试()0018F634

ABC〜Test()0018F634

〜TestWrapper )0018F854

ABC〜Test()003D8490



为什么有两个调用Test destructor,虽然只创建一个Test对象。在它们之间是否创建了任何临时对象?

解决方案方案

您的输出不考虑Test的复制构造函数, std :: vector 很容易使用。



你看到的创建的Test对象是临时传递给 push_back(),而不是向量


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::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.

这篇关于两次调用destructor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 09:43