返回中使用什么构造函数或运算符(C ++) [英] What constructor or operator is used in a return (C++)
本文介绍了返回中使用什么构造函数或运算符(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我运行这段代码来尝试复制构造函数和赋值运算符
I run this code for experimenting copy constructor and assignment operator
class AClass {
private:
int a;
public:
AClass (int a_) : a(a_) {
cout << " constructor AClass(int) " << a << endl;
}
AClass(const AClass & x) : a(x.a) {
cout << " copy constructor AClass(const AClass &) " << a << endl;
}
AClass & operator=(const AClass & x) {
a = x.a;
cout << " AClass& operator=(const AClass &) " << a - endl;
return *this;
}
};
AClass g () {
AClass x(8);
return x;
}
int main () {
cout << " before AClass b = g() " << endl;
AClass b = g();
cout << " after" << endl;
cout << " before AClass c(g()) " << endl;
AClass c (g());
cout << " after" << endl;
}
,发现没有消息显示 return x;
为什么?
这是输出:
before AClass b = g()
constructor AClass(int) 8
after
before AClass c(g())
constructor AClass(int) 8
after
推荐答案
在这种情况下,允许编译器取消复制.这称为返回值优化.
The compiler is allowed to elide copying in a case like this. This is called Return Value Optimization.
这篇关于返回中使用什么构造函数或运算符(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文