c++隐式复制构造函数和赋值操作符

c++ implicit copy constructor and the assignment operator

本文关键字:赋值操作符 构造函数 复制 c++      更新时间:2023-10-16

我有一个定义如下的类:

#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.