专栏首页C++核心准则原文翻译C++核心准则C.152:永远不要将派生类数组的指针赋值给基类指针

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

原文链接:

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


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

关注【面向对象思考】轻松学习每一天!

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

本文分享自微信公众号 - 面向对象思考(OOThinkingDalian),作者:面向对象思考

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2020-02-25

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • C++核心准则边译边学-摘要

    This document is a set of guidelines for using C++ well. The aim of this documen...

    面向对象思考
  • C++核心准则CP.2:避免数据竞争​

    Unless you do, nothing is guaranteed to work and subtle errors will persist.

    面向对象思考
  • C++核心准则ES.84:不要定义无名局部变量

    ES.84: Don't try to declare a local variable with no name

    面向对象思考
  • 通过共分割实现基于涂鸦的域自适应

    中文摘要:虽然深卷积网络在许多医学图像分割任务中已经达到了最先进的性能,但它们通常表现出较差的泛化能力。为了能够从一个领域(例如,一种成像模式)归纳到另一个领域...

    用户7454122
  • Tracking Emerges by Colorizing Videos

    Carl Vondrick , Abhinav Shrivastava , Alireza Fathi , Sergio Guadarrama ,Kevin M...

    用户1908973
  • hbase_异常_01_Hbase: Failed to become active master

    参考:Hbase: Failed to become active master 的解释:

    shirayner
  • mydumper安装笔记

    参考:http://www.tuicool.com/articles/2eAVVvN

    二狗不要跑
  • 一些Cloud for Customer的客户需求

    Partner has created his own stable anchor to point to his embedded component EC_...

    Jerry Wang
  • 使用WebAssembly和Go编写前端Web框架

    JavaScript Frontend frameworks have undoubtedly helped to push the boundaries of...

    李海彬
  • 第2节:英语中的形容词,副词,动词,动名词,动词不定式

    形容词是用来修饰名词的,什么是形容词呢?是用来描述事物或者人的性质和特征的 ,形容词分性质形容词和叙述形容词。

    达达前端

扫码关注云+社区

领取腾讯云代金券