为什么在这里称为复制构造函数
Why is the copy constructor being called here?
#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中使用手表时,表明a
中x
的值甚至在调用了超载分配运算符之前更改。
那么,为什么在这里调用复制构造函数?
,因为您从分配运算符中返回。它应该返回参考:
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;
}
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 复制构造函数、赋值运算符C++
- std::ofstream 作为类成员删除复制构造函数?
- 复制构造函数C++无法正确复制指针
- 关于复制构造函数的一个棘手问题
- 为什么调用复制构造函数而不是移动构造函数?
- 填充上编译器生成的复制构造函数之间的不一致
- C++ 对象指针数组的复制构造函数
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 防止在复制构造函数中隐式调用基构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 具有已删除移动和复制构造函数的类的就地构造
- 复制构造函数隐式转换问题
- 复制构造函数中的递归调用