ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 不正确的强制转换 – 是未定义行为的强制转换或使用

2019-10-04 13:17:28  阅读:184  来源: 互联网

标签:c language-lawyer undefined-behavior casting


如果我从Base转换为Derived类型,但Base类型不是派生类型的实例,但只使用结果,是否会得到未定义的行为?

很难理解我在问什么?看看这个例子:

struct Animal { int GetType(){...} };
struct Dog : Animal { bool HasLoudBark(){...}};
struct Cat : Animal { bool HasEvilStare(){...} };

Animal * a = ...;
Dog* d = static_cast<Dog*>(a);

if(a->GetType() == DogType && d->HasLoudBark())
    ....

在这种情况下,可能是或不是狗.我们总是对狗* d进行静态播放但我们从不使用d,除非我们确定它是一只狗.

假设a不是狗,那么这个未定义的行为是否在演员阵容中?或者它被定义为我们实际上不使用d除非它真的是一只狗?

赞赏参考标准的相关部分.

(是的,我知道我可以使用dynamic_cast和RTTI,可能这不是很好的代码,但我对这是否有效更感兴趣)

解决方法:

演员本身有不确定的行为.引用C 17(n4659)[expr.static.cast] 8.2.10 / 11:

A prvalue of type “pointer to cv1 B”, where B is a class type, can be converted to a prvalue of type “pointer
to cv2 D”, where D is a class derived (Clause 13) from B, if cv2 is the same cv-qualification as, or greater
cv-qualification than, cv1. … If the prvalue of
type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer
points to the enclosing object of type D. Otherwise, the behavior is undefined.

标签:c,language-lawyer,undefined-behavior,casting
来源: https://codeday.me/bug/20191004/1853101.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有