我对返回值优化有些困惑,这里是一个例子。
我有点困惑B 100和D 100输出的含义。
1)为什么编译器会给出“B 100”输出,应该是RVO(不应该调用复制构造函数)。
2)第二个问题是,如果调用了复制构造函数,则“D 100”应该在“B 100”之前,因为在“fun()”函数中对象超出了范围,在“A b = f(a);”语句之前。
#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);”语句之前。
f
的复制品并不是OP正在询问的那个。 OP在问第二个副本。 - Chris Drewfun()
的对象会被销毁?也就是说,当A b=f(a);
结束时,对象会被销毁? - user5028722B 100
?D 100
:( :( - user5028722