相关疑难解决方法(0)

两次调用析构函数

对于以下代码:

#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");
}
Run Code Online (Sandbox Code Playgroud)

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

TestWrapper()0018F854
ABC测试()0018F634
ABC~测试()0018F634
~TestWrapper()0018F854
ABC~测试()003D8490

尽管只创建了一个Test对象,为什么有两次调用Test析构函数.两者之间是否创建了临时对象?如果是,为什么没有调用其相应的构造函数?

我错过了什么吗?

c++

1
推荐指数
1
解决办法
273
查看次数

标签 统计

c++ ×1