C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
C.152:永遠不要將派生類數組的指針賦值給基類指針
Reason(原因)
Subscripting the resulting base pointer will lead to invalid object access and probably to memory corruption.
作爲賦值結果的基類指針的下標運算會引起無效的對象訪問並可能發生內存破壞。
Example(示例)
struct B { int x; };
struct D : B { int y; };
void use(B*);
D a[] = {{1, 2}, {3, 4}, {5, 6}};
B* p = a; // bad: a decays to &a[0] which is converted to a B*
p[1].x = 7; // overwrite D[0].y
use(a); // bad: a decays to &a[0] which is converted to a B*
Enforcement(實施建議)
-
Flag all combinations of array decay and base to derived conversions.
-
提示所有數組退化和基類類型向派生類類型轉換的情況。
-
Pass an array as a span rather than as a pointer, and don't let the array name suffer a derived-to-base conversion before getting into the span
-
使用span傳遞數組而不是指針,也不要再放入span之前讓數組名經過一次派生類向基類類型的轉換。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c151-use-make_shared-to-construct-objects-owned-by-shared_ptrs
覺得本文有幫助?歡迎點贊並分享給更多的人。
閱讀更多更新文章,請關注微信公衆號【面向對象思考】