C++ 隐式复制构造函数和赋值运算符

标签 c++

我有一个定义如下的类:

#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 中。

关于C++ 隐式复制构造函数和赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5590391/

相关文章:

c++ - 如何使 QToolButton 中的图标居中?

c++ - 错误 C2678 : binary '+' : no operator found which takes a left-hand operand of type 'volatile A' (or there is no acceptable conversion)

c++ - 如何在 C++ 中将 little-endian 64 转换为主机字节顺序

c++ - 使用 Boost.asio 并行 Ping(ICMP) 多个目的地

c++ - 什么样的数据或函数放在C++类的保护区比较好?

C++ 线性代数库 Armadillo : how to use eig_pair to get the same result as eig function in Matlab?

c++ - 我究竟该如何使用 Boost?

c++ - 特定于平台的 lib 文件应如何命名?

c++ - 在类中使用数组时出现问题 (C++)

c++ - 如何将 Gabor 滤波器与 Sobel 和 DFT 滤波器输出一起使用