对于下面的代码:两个调用析构函数
#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");
}
这是我在我的MSVC++编译器得到的输出:
TestWrapper()0018F854
ABC测试()0018F634
ABC〜测试()0018F634
〜TestWrapper()0018F854
ABC〜测()003D8490
为什么re是两个对Test析构函数的调用,尽管只创建了一个Test对象。在两者之间是否有任何临时对象?如果是,为什么没有调用其相应的构造函数?
我错过了什么吗?
你说过“临时对象被复制到向量中后会被销毁”。 最后的析构函数调用是用于临时对象的。为什么不立即销毁? – 2009-12-25 06:42:41
不,第一个析构函数调用是用于临时对象的。临时对象由一个字符串参数构造,这就是为什么你看到被调用的构造函数。 – Artelius 2009-12-25 06:50:20
那么为什么“这个”类似的这两个值: ABC测试()0018F634 ABC〜测()0018F634 – 2009-12-25 07:32:46