【发布时间】:2014-08-02 13:13:55
【问题描述】:
我写了这样一个简单的代码:
class Test
{
public:
Test()
{
cout << "Constructor called." << endl;
}
~Test()
{
cout << "Destructor called." << endl;
}
Test(const Test& test)
{
cout << "Copy constructor called." << endl;
}
void Show() const
{
cout << "Show something..." << endl;
}
};
Test Create()
{
return Test();
}
int main()
{
Create().Show();
}
这段代码的输出是:
Constructor called.
Show something...
Destructor called.
但是当我像这样修改函数 Create() 时:
Test Create()
{
Test test;
return test;
}
输出是:
Constructor called.
Copy constructor called.
Destructor called.
Show something...
Destructor called.
为什么匿名对象不调用拷贝构造函数和析构函数?请帮帮我,谢谢。
【问题讨论】:
-
了解copy elision。
标签: c++