为什么在这里称为复制构造函数

Why is the copy constructor being called here?

本文关键字:复制 构造函数 在这里 为什么      更新时间:2023-10-16
#include <iostream>
using namespace std;
class A
{
    int x;
public:
    A(int a)
    {   
        x = a;
        cout << "CTOR CALLED";
    }
    A(A &t)
    {
        cout << "COPY CTOR CALLED";
    }
    void display()
    {
        cout << "Random stuff";
    }
    A operator = (A &d)
    {   
        d.x = x;
        cout << "Assignment operator called";
        return *this;
    }
};
int main()
{
    A a(3), b(4);
    a = b;
    return 0;
}

此代码的输出是:

ctor称为
CTOR称为
分配运营商称为
复制ctor称为

当我在Visual Studio中使用手表时,表明ax的值甚至在调用了超载分配运算符之前更改。

那么,为什么在这里调用复制构造函数?

,因为您从分配运算符中返回。它应该返回参考

A& operator = (A &d) { ... }

as @someProgrammerdude已经说过,这是因为您按值返回,而不是像通常使用分配运算符那样通过参考。我想补充一点,您的任务运营商当前是错误的:

A operator = (A &d)
{   
    d.x = x;
    cout << "Assignment operator called";
    return *this;
}

通常您是通过const参考传递d,因为我们想更改this的成员。您正在更改d的成员。这将在功能上将您的a = b;变成b = a;,因为a = b;现在实际上更改了b的成员!

使d A const&阻止了这些错误。

您应该将其更改为:

A& operator = (A const &d)
{   
    x = d.x;
    cout << "Assignment operator called";
    return *this;
}