如题,为什么会这样啊,理论上来说,函数返回了,局部对象会析构吧,如果不生产个临时对象,怎么把对象返回呢。
class Test{
public:
Test(){cout << "Test::Test()" << endl;}
~Test(){ cout << "Test::~Test()" << endl;}
};
Test func()
{
return Test();
}
int main()
{
func();
return 0;
}
运行结果:
Test::Test()
Test::~Test()
这里只产生了一个对象,并没有看到函数返回时的临时对象。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这个叫做 返回值优化(RVO)。(编译器帮你省掉了而已)
请见 http://zh.wikipedia.org/zh/%E8%BF%94%E5%9B%9E%E5%80%BC%E4%BC%98%E5%8C%96