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

面向对象思考

共 2058字,需浏览 5分钟

 ·

2020-01-15 23:23

e9ff23422dba897e2c6d139287fc032d.webp

蓝铜矿

//

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(反面示例)

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(示例)

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);
303eab9430f7fc711a6d1dc18ba5f776.webp

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

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

b0f21767f30db1ee10a0196b0ecb061d.webp




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




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

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

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



浏览 34
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报