【发布时间】:2015-08-27 15:44:51
【问题描述】:
我对返回值优化有点困惑,这里是例子。
#include <iostream>
using namespace std;
class A{
int x;
public:
A(int val=0):x(val){
cout << "A" << x << endl;
}
A(const A& a){
x=a.x;
cout << "B " << x << endl;
}
void SetX(int x){
this -> x=x;
}
~A(){
cout << "D " << x << endl;
}
};
A f(A a){
cout << "C " << endl;
a.SetX(100);
return a;
}
int main(){
A a(1);
A b=f(a); // Why Copy constructor instead of RVO?
b.SetX(-100);
return 0;
}
输出
A 1 // ok
B 1 // ok
C // ok
B 100 // why it's here? Why copy constructor instead of RVO?
D 100 // why after the above line? it should be before the above line.
D -100 // ok
D 1 // ok
我对 B 100 和 D 100 输出有点困惑。
1) 为什么编译器给出B 100 的输出应该是RVO(不应该调用复制构造函数)。
2) 第二个是如果调用复制构造函数,那么D 100 应该在B 100 之前,因为在fun() 中,函数对象超出了范围。在A b=f(a); 声明之前。
【问题讨论】:
标签: c++