c++隐式复制构造函数和赋值操作符
c++ implicit copy constructor and the assignment operator
我有一个定义如下的类:
#include <iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(int a, int b) : x(a), y(b)
{
std::cout << "Constructing point ( " << a << ", " << b << " ) "
<< std::endl;
}
Point(const Point& p) : x(p.x), y(p.y)
{
std::cout << "In copy constructor " << p.x << " " << p.y
<< std::endl;
}
Point& operator=(const Point& p)
{
std::cout << "In assignment operator " << p.x << " " << p.y
<< std::endl;
x = p.x;
y = p.y;
return *this;
}
};
int main()
{
Point p1 = Point(1, 2);
return 0;
}
现在当我执行这个时,我看到的都是Constructing point (1, 2)
。我假设编译器在这里做了一些优化。它是正确的,在理论上临时得到构造,然后调用赋值操作符初始化p1?
不,在这样的声明中,=
操作符实际上仍然意味着调用构造函数,并且编译器可能省略了任何可能的复制构造作为优化。声明中的=
永远不会导致调用赋值。因此,理论上可以创建一个临时文件并将其复制到p1
中。
如果您希望看到操作符=被调用,您必须编写如下代码:
Point p1(5, 5);
Point p2(0, 0); //You don't have a default constructor.
p2 = p1; // Now operator = is called.
相关文章:
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 错误的数组初始化与赋值副本构造函数初始化
- 赋值复制构造函数
- 复制构造函数,赋值操作符重载
- 通过调用Move赋值操作符实现Move构造函数
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 类赋值操作符和复制构造函数
- 影响正确性的move构造函数/赋值操作符示例
- 如果没有定义Move语义(Move构造函数和Move赋值操作符),编译器是否默认优化
- 即使类没有定义构造函数,也不能在类上调用c++默认的move赋值操作符
- 复制构造函数和赋值操作符都被调用
- 与智能指针相关的c++移动语义与复制构造函数和赋值操作符
- 为什么不是只有一个?复制构造函数和赋值操作符
- c++析构函数、复制构造函数和赋值操作符实践考试
- 为什么这里需要构造函数和赋值操作符
- 赋值给构造函数中的常量变量
- 成员初始化列表vs赋值/复制构造函数(在boost deadline_timer中)
- 将传递的对象赋值给构造函数中的成员对象