前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则T.​81:不要混用继承层级和数组

C++核心准则T.​81:不要混用继承层级和数组

作者头像
面向对象思考
发布2020-09-28 16:37:07
4130
发布2020-09-28 16:37:07
举报

T.81: Do not mix hierarchies and arrays

T.81:不要混用继承层级和数组

Reason(原因)

An array of derived classes can implicitly "decay" to a pointer to a base class with potential disastrous results.

派生类的数组可以隐式退化为可能带来灾难性后果的指向基类的指针。

Example(示例)

Assume that Apple and Pear are two kinds of Fruits.

假定Apple和Pear是两种Fruit。

代码语言:javascript
复制
void maul(Fruit* p)
{
    *p = Pear{};     // put a Pear into *p
    p[1] = Pear{};   // put a Pear into p[1]
}

Apple aa [] = { an_apple, another_apple };   // aa contains Apples (obviously!)

maul(aa);
Apple& a0 = &aa[0];   // a Pear?
Apple& a1 = &aa[1];   // a Pear?

Probably, aa[0] will be a Pear (without the use of a cast!). If sizeof(Apple) != sizeof(Pear) the access to aa[1] will not be aligned to the proper start of an object in the array. We have a type violation and possibly (probably) a memory corruption. Never write such code.

很有可能aa[0]是一个Pear(不需要类型转化)。如果sizeof(Apple)!=sizeof(Pear),对于aa[1]的访问位置就不会正确开始于下个对象。我们会遇到类型违反和可能的(几乎一定)内存破坏。永远不要这样写代码。

Note that maul() violates the a T* points to an individual object rule.

Alternative: Use a proper (templatized) container:

注意maul()已经违反了使用T*或onwer<T*>指明唯一对象原则。其他选项:使用适当的(模板化的)容器。

代码语言:javascript
复制
void maul2(Fruit* p)
{
    *p = Pear{};   // put a Pear into *p
}

vector<Apple> va = { an_apple, another_apple };   // va contains Apples (obviously!)

maul2(va);       // error: cannot convert a vector<Apple> to a Fruit*
maul2(&va[0]);   // you asked for it

Apple& a0 = &va[0];   // a Pear?

Note that the assignment in maul2() violated the no-slicing rule.

注意maul2()中的赋值操作违反了不要分割对象原则。

Enforcement(实施建议)

  • Detect this horror! 检出这种可怕的问题!

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t81-do-not-mix-hierarchies-and-arrays

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-09-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档