隐式复制构造函数/赋值运算符的行为
我有一个关于 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?
Thank you for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果派生类没有声明复制构造函数,则将声明隐式复制构造函数(12.8/4“复制类对象”) - 即使基类具有用户定义和定义的复制构造函数。如果在这种情况下基类具有用户定义的复制构造函数,则使用该用户定义的复制构造函数复制该基类子对象 (12.8/8)。
复制赋值运算符也类似(12.8/10 和 12.8.13)。
因此,如果派生类不需要用户定义的复制构造函数或复制赋值运算符来“它自己的东西”,则不一定需要实现调用基类的用户定义版本。但是,如果派生类确实声明并定义了自己的复制构造函数/复制赋值运算符,那么就基类子对象而言,这些用户定义的实现负责做正确的事情 - 不再由编译器自动。
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.
仅当派生类具有显式定义的运算符函数时。否则,调用父类的op函数。否则,将调用隐式 C++ 函数。
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.