可能重复:
Why copy constructor is not called in this case?
What is copy elision and how does it optimize the copy-and-swap idiom?
我正在试图理解ctors和运算符重载。
#include <iostream>
using namespace std;
class number {
int n;
public:
number(int i=0):n(i) { cout<<"in ctor"<<endl; }
~number() { cout<<"in dtor"<<endl; }
number(const number& obj):n(obj.n) {
cout<<"in copy ctor"<<endl; }
number operator+(const number & obj) {
return number(n+obj.n); }
number operator=(const number &rhs) {
n = rhs.n; cout<<"in assignemnt opr"<<endl; }
void disp() {cout<<n<<endl;}
};
int main()
{
number one(1),two(2);
number three =one + two; //was expecting copy ctor being called here
three.disp();
}
当我运行上面的代码时,我得到了以下输出
我理解在重载的one
运算符中调用了三个构造函数two
,un-named
和+
对象。我无法理解three
如何我想要复制ctor应该被调用。但它似乎不是。
有人可以解释一下。感谢。