隐式拷贝构造函数/赋值运算符的行为 [英] behaviour of the implicit copy constructor / assignment operator

查看:528
本文介绍了隐式拷贝构造函数/赋值运算符的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于C ++标准的问题。

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?

感谢您的帮助。

推荐答案

如果派生类没有声明一个复制构造函数,隐式的一个将被声明(12.8 / 4复制类对象) - 即使基类有一个用户delcared定义的复制构造函数。如果基类在这种情况下具有用户定义的复制构造函数,那么使用该用户定义的复制ctor(12.8 / 8)复制该基类子对象。

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).

对于拷贝赋值运算符(12.8 / 10和12.8.13),同样如此。

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

所以你不一定需要实现调用基类的用户定义的版本类不需要为自己的东西的用户定义的复制ctor或复制赋值运算符。然而,如果派生类声明并定义了它自己的拷贝ctor / copy赋值运算符,那么这些用户定义的实现就负责做正确的事情,就基类子对象而言 - 不再由编译器自动。

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.

这篇关于隐式拷贝构造函数/赋值运算符的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆