C++核心准则C.145:通过指针或引用访问多态对象
C.145: Access polymorphic objects through pointers and references
C.145:通过指针或引用访问多态对象
Reason(原因)
If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.
如果类有虚函数,通常不会知道使用的函数具体是由那个(派生)类提供的。
Example(示例)
struct B { int a; virtual int f(); virtual ~B() = default };
struct D : B { int b; int f() override; };
void use(B b)
{
D d;
B b2 = d; // slice
B b3 = b;
}
void use2()
{
D d;
use(d); // slice
}
Both ds are sliced.
两个(函数中的)d都被切断了(因为派生类对象向基类对象赋值,译者注)
Exception (例外)
You can safely access a named polymorphic object in the scope of its definition, just don't slice it.
你可以在多态对象被定义的作用域中通过变量名安全地使用它,只要注意不被切断就行。
void use3()
{
D d;
d.f(); // OK
}
See also(参见)
A polymorphic class should suppress copying(多态类应该抑制复制)
Enforcement
Flag all slicing.(标记发生数据切断的操作)
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c145-access-polymorphic-objects-through-pointers-and-references
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!
评论