C++核心準則C.145:通過指針或引用訪問多態(tài)對象

C.145: Access polymorphic objects through pointers and references
C.145:通過指針或引用訪問多態(tài)對象
Reason(原因)
If you have a class with a virtual function, you don't (in general) know which class provided the function to be used.
如果類有虛函數(shù),通常不會知道使用的函數(shù)具體是由那個(派生)類提供的。
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.
兩個(函數(shù)中的)d都被切斷了(因為派生類對象向基類對象賦值,譯者注)
Exception (例外)
You can safely access a named polymorphic object in the scope of its definition, just don't slice it.
你可以在多態(tài)對象被定義的作用域中通過變量名安全地使用它,只要注意不被切斷就行。
void use3()
{
D d;
d.f(); // OK
}
See also(參見)
A polymorphic class should suppress copying(多態(tài)類應(yīng)該抑制復(fù)制)
Enforcement
Flag all slicing.(標記發(fā)生數(shù)據(jù)切斷的操作)
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c145-access-polymorphic-objects-through-pointers-and-references
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評論
圖片
表情
