不正确的转换-是未定义行为的转换还是使用 [英] Incorrect cast - is it the cast or the use which is undefined behavior

查看:90
本文介绍了不正确的转换-是未定义行为的转换还是使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将类型从Base强制转换为Derived类型,但Base类型不是派生类型的实例,而是仅使用结果,是否会得到不确定的行为?

If I do a cast from a Base to a Derived type, but the Base type isn't an instance of derived type, but only use the result if it is, do I get undefined behaviour?

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

Hard to understand what I'm asking? take a look at this example:

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())
    ....

在这种情况下,a可能是Dog,也可能不是.我们始终将astatic_cast用作Dog * d,但除非确定其为Dog,否则我们从不使用d.

In this case a may or not be a Dog. We always do the static_cast of a to Dog * d but we never use d unless we're sure its a Dog.

假设a不是Dog,在转换时是否存在这种未定义的行为?还是将其定义为我们实际上并不使用d,除非它确实是Dog?

Assuming that a is not a Dog, is this undefined behaviour at the point of the cast? Or is it defined as we don't actually use d unless it is really is a Dog?

请参考该标准的相关部分.

References to the relevant parts of the standard are appreciated.

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

(Yes I know I can use dynamic_cast, and RTTI, and probably this isn't great code, but I'm more interested in whether this is valid)

推荐答案

演员表本身具有未定义的行为.引用C ++ 17(n4659)[expr.static.cast] 8.2.10/11:

The cast itself has undefined behaviour. Quoting C++17 (n4659) [expr.static.cast] 8.2.10/11:

" cv1 B的指针"类型的prvalue,其中B是一个类类型,可以转换为"pointer指针"类型的prvalue 到 cv2 D",其中D是从B派生的类(第13条),如果 cv2 与cv-qualification相同或更高 cv资格认证,而不是 cv1 . ...如果 类型指向 cv1 B的指针"指向实际上是类型为D的对象的子对象的B,生成的指针 指向类型为D的封闭对象.否则,行为是不确定的.

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.

这篇关于不正确的转换-是未定义行为的转换还是使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆