C++核心准则C.152:永远不要将派生类数组的指针赋值给基类指针

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之前让数组名经过一次派生类向基类类型的转换。

    扫描二维码关注公众号,回复: 11205027 查看本文章

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c151-use-make_shared-to-construct-objects-owned-by-shared_ptrs


觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

原创文章 414 获赞 724 访问量 35万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/105642519
今日推荐