Incorrect cast - is it the cast or the use which is undefined behavior

前端 未结 2 1706
抹茶落季
抹茶落季 2020-12-29 02:38

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?

H

2条回答
  •  我在风中等你
    2020-12-29 02:59

    This is undefined behaviour, but (funny enough) if you would have used reinterpret_cast instead of static_cast, you would cast that demon away.

    [expr.reinterpret.cast]/7

    An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_­cast(static_­cast(v)).

    As noted by user Angew, this "requires a particular internal representation which ensures that static_cast(d) == static_cast(a) when a == d".

    This is expressed by [class.mem]/22 to 26:

    [class.mem]/26

    If a standard-layout class object has any non-static data members, its address is the same as the address of its first non-static data member if that member is not a bit-field. Its address is also the same as the address of each of its base class subobjects.

    So if GetType() of Animal returns the value of a non-static data member from the common initial sequence of Animal and Dog, the behavior is defined.

    Those requirements are met when dealing with simple inheritance and default-aligned objects.

提交回复
热议问题