02.25 永远不要将派生类数组赋值给基类类型指针

永远不要将派生类数组赋值给基类类型指针

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(示例)

<code>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].yuse(a);       // bad: a decays to &a[0] which is converted to a B*/<code>


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


觉得本文有帮助?请分享给更多人。

面向对象开发,面向对象思考!


分享到:


相關文章: