对于以下代码:
#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++ 编译器上得到的输出:
测试包装器()0018F854
ABC 测试() 0018F634
ABC ~测试() 0018F634
〜测试包装器()0018F854
ABC ~测试() 003D8490
尽管只创建了一个 Test 对象,但为什么有两次对 Test 析构函数的调用。中间是否创建了任何临时对象?如果是,为什么没有调用其对应的构造函数?
我错过了什么吗?
您的输出不考虑测试的复制构造函数,它std::vector
很容易使用。
您看到创建的测试对象是临时传递给push_back()
,而不是实际中的那个vector
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)