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

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

问题描述

我有一个关于 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《复制类对象》)——即使基类有一个用户定义和定义的复制构造函数.如果在这种情况下基类具有用户定义的复制构造函数,则使用该用户定义的复制 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/复制赋值运算符,那么就基类子对象而言,那些用户定义的实现负责做正确的事情——这不再由自动编译.

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天全站免登陆