提供赋值运算符但不提供复制构造函数

发布于 2024-12-05 19:29:11 字数 183 浏览 1 评论 0原文

我在这里读到如果我不写编译器为我使用的复制构造函数 赋值运算符,这会导致对象的浅复制。如果我有的话怎么办 赋值运算符在我的所有成员对象中重载?这不会导致深复制吗?

I read here that if I don't write a copy constructor the compiler does it for me using
the assignment operator, which results in shallow copy of Objects. What if I do have the
assignment operator overloaded in all of my member object? wouldn't it result in a deep copy?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

软糖 2024-12-12 19:29:11

如果我不编写复制构造函数,编译器会使用赋值运算符为我编写复制构造函数

不,它不使用赋值运算符;它通过隐式生成的复制构造函数来执行浅复制。

如果我的所有成员对象中都重载了赋值运算符怎么办?这不会导致深复制吗?

鉴于在没有显式定义的复制构造函数的情况下不使用赋值运算符,即使您重载了赋值运算符,您仍然需要重载复制构造函数。

阅读 C++ 中的三法则 03& 五规则在 C++11 中。

if I don't write a copy constructor the compiler does it for me using the assignment operator

No, it doesn't use the assignment operator; it does it via a implicitly generated copy constructor which does a shallow copy.

What if I do have the assignment operator overloaded in all of my member object? wouldn't it result in a deep copy?

Given that the assignment operator is not used in absence of explicitly defined copy constructor, even though you have the assignment operator overloaded you still need to overload the copy constructor as well.

Read the Rule of Three in C++03 & Rule of Five in C++11.

阿楠 2024-12-12 19:29:11

链接文章中的重要部分是“类的每个成员单独使用赋值运算符”。因此,如果您为类定义赋值运算符并不重要,它将为类的每个成员使用赋值运算符。

The important part in the linked article is "each member of the class individually using the assignment operator." So it doesn't matter if you define the assignment operator for you class, it will use the assignment operator for each member of your class.

梅倚清风 2024-12-12 19:29:11

你被误导了。隐式生成的构造函数和赋值运算符只是对所有成员和子对象递归地执行构造或赋值:

  • 复制构造函数逐个元素复制

  • 移动构造函数逐个元素移动

  • 复制赋值逐个元素赋值

  • move allocate 逐个元素移动分配

这逻辑是最好的设计的原因在其中,您自己不编写任何复制构造函数(或其他三个中的任何一个,或析构函数),而是编写精心选择的单一职责类,这些类自己的语义会处理所有事情。

You're misinformed. The implicitly generated constructors and assignment operators simply perform construction or assignment recursively on all members and subobjects:

  • copy constructor copies element by element

  • move constructor moves element by element

  • copy assignment assigns element by element

  • move assign move-assigns element by element

This logic is the reason why the best design is one in which you don't write any copy constructor (or any of the other three, or the destructor) yourself, and instead compose your class of well-chosen, single-responsibility classes whose own semantics take care of everything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文