复制构造函数、按值传递和按值返回、链式操作、编译器
copy constructor, pass by value and return by value, chain operation, compiler
我在两个不同的编译器中编写了这个程序,得到了两个不同结果:
#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; }
否则,可能会发生不必要的复制。最有可能的情况是,创建一个进入赋值运算符的副本,然后将返回的值复制到p2
和p1
。
相关文章:
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 如何将操作委托给函数返回
- 是否有一个C++函数可以准确返回平方根反比的内置 CPU 操作 RSQRTSS 的值?
- 复制构造函数、按值传递和按值返回、链式操作、编译器
- 如何仅覆盖一个EXPECT_CALL的默认ON_CALL操作,并在以后返回到默认操作
- 如何检查正确操作数以通过参考返回功能
- 返回指向操作+的结果的指针
- 尝试修改 sqlite3 插入以返回 PK。 不确定如何使用 sqlite3 专门执行此操作
- 在我的Matrix4类中使用某些用户定义的运算符的操作正在返回高值的高值
- 继承的加法赋值操作,如何返回正确的类型
- 堆栈弹出操作是否可以安全地返回 C++11 中的值
- 为什么计数和擦除等unordered_set操作会返回size_type
- 对向量进行操作后返回时出错
- C++类函数返回值 VS 对本地数据进行操作
- 通过互操作调用方法,该方法返回结构的实例
- C++ STL容器集和多集:不同返回类型的插入操作
- 在以下代码中执行删除操作时,我无法获得以下代码中返回的正确值
- 如何在返回SQLite中零项的SELECT操作中获取列名
- 从语义操作返回的值会干扰规则属性
- iomanip操作返回一个十六进制值