#include <iostream>
using namespace std;
class A {
public:
A() {
cout << this << " constructor" << endl;
}
A(const A &obj) {
cout << this << " copy constructor" << endl;
}
A &operator=(const A &a) {
cout << this << " operator=" << endl;
return *this;
}
~A() {
cout << this << " destructor" << endl;
}
};
// 反正都是构造a, 那么我们直接在func内部对a进行构造可以吧
A func() {
A temp;
cout << "temp " << &temp << endl;
return temp;
}
int main() {
A a(func());
cout << "a " << &a << endl;
/* A b; b = func(); */
return 0;
}
看A a(func())
这个过程,正常情况下,应该有个中间的匿名变量来传递中间值,然后temp构造,拷贝给匿名中间值,然后在拷贝给a。
毕竟一个函数执行完就是执行完了,怎么可能知道函数外面的东西,
所以,这个中间值是应该存在的才对,就像是实参一样,不过是没有名字的。
但是实际上的输出确是
0x7ffcc540daff constructor
temp 0x7ffcc540daff
a 0x7ffcc540daff
0x7ffcc540daff destructor
temp和a是一个东西,这就是返回值优化,既然temp和a完全一模一样,那么我直接在func中初始化a不就完了,
也就是把temp当做a的一个引用来初始化。
g++ -fno-elide-constructors
当然可以使用这个命令来关闭返回值优化
输出结果为以下的内容,
就是使用一个中间匿名变量的值的过程
0x7ffeaf55e84f constructor
temp 0x7ffeaf55e84f
0x7ffeaf55e87f copy constructor
0x7ffeaf55e84f destructor
0x7ffeaf55e87e copy constructor
0x7ffeaf55e87f destructor
a 0x7ffeaf55e87e
0x7ffeaf55e87e destructor