开发者

providing assignment operator but no copy constructor

开发者 https://www.devze.com 2023-04-06 17:54 出处:网络
I read here that if I开发者_开发知识库 don\'t write a copy constructor the compiler does it for me using

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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号