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

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