复制构造函数、按值传递和按值返回、链式操作、编译器

copy constructor, pass by value and return by value, chain operation, compiler

本文关键字:操作 返回 编译器 构造函数 按值传递 复制      更新时间:2023-10-16

我在两个不同的编译器中编写了这个程序,得到了两个不同结果:

#include <iostream>
using namespace std;
class Point {
public:
int n;
Point() { n = 0; }
Point operator= (Point p) { return *this; }
Point(const Point& p) { cout<<"copyn"; }
~Point() { cout<<"Destructn"; }
};
int main() {
Point p1, p2, p3;
p1 = p2 = p3;
return 0;
}

编译器1:

copy
copy
copy
Destruct
Destruct
Destruct
Destruct
Destruct
Destruct

编译器2:

copy
copy
Destruct
copy
Destruct
Destruct
Destruct
Destruct
Destruct

我知道有些编译器通过不调用复制构造函数来优化函数中对象的传递/返回值。这就是两个结果之间存在差异的原因吗?

更重要的是,为什么复制构造函数对代码的p2=p3部分调用了两次,而对p1=…只调用了一次

我不怎么使用C++进行OO编程,这就是为什么我对这个简单的问题感到困惑。我真的很感激的一些提示

您的赋值运算符应该返回Point &而不是Point,并且它也应该将参数作为引用:

Point &operator = (const Point &p) { return *this; }

否则,可能会发生不必要的复制。最有可能的情况是,创建一个进入赋值运算符的副本,然后将返回的值复制到p2p1