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

2f033def6c736b6c1a96b3469ba39c7a.png

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].yuse(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


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

更多精彩文章欢迎关注微信公众号【面向对象思考】!

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值