洞察探讨小游戏SDK接入的最佳实践以及对企业跨平台开发的优势
564
2022-11-12
C++核心准则C.67:多态类应该抑制拷贝
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 copyingpublic: 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 copyingpublic: 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引入的新特性,具体请参照作者的以下文章:
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(实施建议)
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c67-a-polymorphic-class-should-suppress-copying
觉得本文有帮助?欢迎点赞并分享给更多的人。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~