提供赋值运算符但不提供复制构造函数
我在这里读到如果我不写编译器为我使用的复制构造函数 赋值运算符,这会导致对象的浅复制。如果我有的话怎么办 赋值运算符在我的所有成员对象中重载?这不会导致深复制吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,它不使用赋值运算符;它通过隐式生成的复制构造函数来执行浅复制。
鉴于在没有显式定义的复制构造函数的情况下不使用赋值运算符,即使您重载了赋值运算符,您仍然需要重载复制构造函数。
阅读 C++ 中的三法则 03& 五规则在 C++11 中。
No, it doesn't use the assignment operator; it does it via a implicitly generated copy constructor which does a shallow 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.
链接文章中的重要部分是“类的每个成员单独使用赋值运算符”。因此,如果您为类定义赋值运算符并不重要,它将为类的每个成员使用赋值运算符。
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.
你被误导了。隐式生成的构造函数和赋值运算符只是对所有成员和子对象递归地执行构造或赋值:
复制构造函数逐个元素复制
移动构造函数逐个元素移动
复制赋值逐个元素赋值
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.