Why Doesn't reinterpret_cast Force copy_n for Casts between Same-Sized Types?

后端 未结 2 1167
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 15:20

According to cppreference.com, reinterpret_cast:

Converts between types by reinterpreting the underlying bit pattern.

2条回答
  •  生来不讨喜
    2020-11-30 15:53

    why doesn't reinterpret_cast handle that for me?

    One reason is that the size, alignment, and bit representations aren't specified, so such a conversion wouldn't be portable. However, that wouldn't really justify making the behaviour undefined, just implementation-defined.

    By making it undefined, the compiler is allowed to assume that expressions of unrelated types don't access the same object, which can allow better optimisation. For example, in the following:

    int   & i = something();
    float & f = something_else();
    
    const int i1 = i;
    f = 42;
    const int i2 = i;
    

    the compiler can assume that i1 and i2 both have the same value (i being unchanged by the assignment to f), and optimise them into a single constant. Breaking the assumption will then cause undefined behaviour.

    Or is there something else available so I don't have to jump through this hoop?

    Copying the bytes is the only well-defined way to reinterpret one object type as an unrelated type.

    Aliasing with reinterpret_cast or a union might work sometimes (assuming the size etc. match), but might trip you up if the optimiser gets too clever with undefined behaviour.

提交回复
热议问题