繁体   English   中英

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

如果要查看operator =被调用,则必须编写如下代码:

Point p1(5, 5);
Point p2(0, 0); //You don't have a default constructor.

p2 = p1; // Now operator = is called.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM