前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.67:多态类应该抑制拷贝

C++核心准则C.67:多态类应该抑制拷贝

作者头像
面向对象思考
发布2020-03-25 16:17:37
5690
发布2020-03-25 16:17:37
举报
文章被收录于专栏:C++核心准则原文翻译

//

C.67: A polymorphic class should suppress copying(C.67:多态类应该抑制拷贝)

//

Reason(原因)

A polymorphic class is a class that defines or inherits at least one virtual function. It is likely that it will be used as a base class for other derived classes with polymorphic behavior. If it is accidentally passed by value, with the implicitly generated copy constructor and assignment, we risk slicing: only the base portion of a derived object will be copied, and the polymorphic behavior will be corrupted.

多态类或者定义或者继承了至少一个虚函数。它有可能被用作基类以供其他具有多态行为的派生类继承。如果它通过隐式生成的拷贝构造函数和赋值运算符被意外地以值的形式传递了,这种分层结构会产生风险:只有派生类的基类部分会被拷贝,多态行为的完整性会被破坏。

Example, bad(反面示例)

代码语言:javascript
复制
class B { // BAD: polymorphic base class doesn't suppress copying
public:
    virtual char m() { return 'B'; }
    // ... nothing about copy operations, so uses default ...
};

class D : public B {
public:
    char m() override { return 'D'; }
    // ...
};

void f(B& b) {
    auto b2 = b; // oops, slices the object; b2.m() will return 'B'
}

D d;
f(d);

Example(示例)

代码语言:javascript
复制
class B { // GOOD: polymorphic class suppresses copying
public:
    B(const B&) = delete;
    B& operator=(const B&) = delete;
    virtual char m() { return 'B'; }
    // ...
};

class D : public B {
public:
    char m() override { return 'D'; }
    // ...
};

void f(B& b) {
    auto b2 = b; // ok, compiler will detect inadvertent copying, and protest
}

D d;
f(d);

上述代码中使用的=delete是C++11引入的新特性,具体请参照作者的以下文章:

https://mp.weixin.qq.com/s/5yMBZWlKN_7OWhaJD4u_XQ

Note(注意)

If you need to create deep copies of polymorphic objects, use clone() functions: see C.130.

如果你需要实现多态对象的深拷贝,使用clone函数,参见C.130

Exception(例外)

Classes that represent exception objects need both to be polymorphic and copy-constructible.

表现例外对象的类需要同时拥有多态和可拷贝的特性。

Enforcement(实施建议)

  • Flag a polymorphic class with a non-deleted copy operation.
  • 提示没有将拷贝操作声明为=delete的多态类。
  • Flag an assignment of polymorphic class objects.提示多态类的赋值操作。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c67-a-polymorphic-class-should-suppress-copying


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-01-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档