不正确的转换-是未定义行为的转换还是使用 [英] Incorrect cast - is it the cast or the use which is undefined behavior
问题描述
如果我将类型从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
,也可能不是.我们始终将a
的static_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 到 cv2D
",其中D
是从B
派生的类(第13条),如果 cv2 与cv-qualification相同或更高 cv资格认证,而不是 cv1 . ...如果 类型指向 cv1B
的指针"指向实际上是类型为D
的对象的子对象的B
,生成的指针 指向类型为D
的封闭对象.否则,行为是不确定的.
A prvalue of type "pointer to cv1
B
", whereB
is a class type, can be converted to a prvalue of type "pointer to cv2D
", whereD
is a class derived (Clause 13) fromB
, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. ... If the prvalue of type "pointer to cv1B
" points to aB
that is actually a subobject of an object of typeD
, the resulting pointer points to the enclosing object of typeD
. Otherwise, the behavior is undefined.
这篇关于不正确的转换-是未定义行为的转换还是使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!