behaviour of the implicit copy constructor / assignment operator

蓝咒 提交于 2019-12-02 01:41:19

问题


I have a question regarding the C++ Standard.

Suppose you have a base class with user defined copy constructor and assignment operator. The derived class uses the implicit one generated by the compiler.

Does copying / assignment of the derived class call the user defined copy constructor / assignment operator? Or do you need to implement user defined versions that call the base class?

Thank you for your help.


回答1:


If a derived class does not declare a copy constructor, and implicit one will be declared (12.8/4 "Copying class objects") - even if the base class has a user-delcared and defined copy constructor. If the base class has a user-defined copy constructor in this case, that base class sub-object is copied using that user-defined copy ctor (12.8/8).

Similarly for copy assignment operators (12.8/10 and 12.8.13).

So you do not necessarily need to implement user defined versions that call the base class if the derived class doesn't need a user-defined copy ctor or copy assignment operator for 'its own stuff'. However, if the derived class does declare and define its own copy ctor/copy assignment operator, then those user-defined implementations are responsible for doing the right thing as far as the base class sub-object is concerned - that is no longer handled by the compiler automatically.




回答2:


Only if the derived class has an explicitly defined operator function. Otherwise, the op function of the parent class is called. Otherwise, the implicit C++ one is called.



来源:https://stackoverflow.com/questions/2779316/behaviour-of-the-implicit-copy-constructor-assignment-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!