【发布时间】:2020-08-24 00:14:48
【问题描述】:
#include <iostream>
using namespace std;
class A
{
public :
A()
{
cout<<"constructor is called"<<endl;
}
~A()
{
cout<<"destructor is called"<<endl;
}
A(const A &s)
{
cout<<"copy constructor is called"<<endl;
}
};
A beta()
{
A a;
cout<<"mem location a : "<<&a<<endl;
return a;
}
int main(int argc, char** argv) {
A b = beta();
cout<<"mem location b : "<<&b<<endl;
return 0;
}
上述程序产生以下输出:
constructor is called
mem location a : 0x7ffc12bdaf77
mem location b : 0x7ffc12bdaf77
destructor is called
据我了解,由于复制省略或返回值优化,只创建了一个 A 实例,而不是 A a 和 A b 的 2 个实例。 但是从内存的角度看上面的程序,object a 在函数 beta 的栈激活记录或栈空间内,内存位置为 0x7ffc12bdaf77。当它从 beta 返回时,复制省略使对象 b 与对象 a 相同,而不是复制它。所以,现在 b 也有地址 0x7ffc12bdaf77 。我无法理解 if b 仍然是函数 main 的本地并且存在于它的堆栈空间中,它怎么会占用 main 的堆栈空间之外的内存?
【问题讨论】:
标签: c++ c++11 copy-elision