C99 strict aliasing rules in C++ (GCC)

后端 未结 3 634
我在风中等你
我在风中等你 2020-12-30 01:36

As far as I understand, GCC supports all of its C99 features in C++. But how is C99 strict aliasing handled in C++ code?

I know that casting with C casts between unr

3条回答
  •  孤城傲影
    2020-12-30 02:03

    No, you are probably mixing different things.

    Strict aliasing rules have absolutely nothing to do with C99 standard specifically. Strict aliasing rules are rooted in parts of the standard that were present in C and C++ since the beginning of [standardized] times. The clause that prohibits accessing object of one type through a lvalue of another type is present in C89/90 (6.3) as well as in C++98 (3.10/15). That's what strict aliasing is all about, no more, no less. It is just that not all compilers wanted (or dared) to enforce it or rely on it. Both C and C++ languages are sometimes used as "high-level assembly" languages and strict aliasing rules often interfere with such uses. It was GCC that made that bold move and decided to start relying on strict aliasing rules in optimizations, often drawing complaints from those "assembly" types.

    It is true that the most straightforward way to break strict aliasing rules in C++ is reinterpret_cast (and C-style cast, of course). However, static_cast can also be used for that purpose, since it allows one to break strict aliasing by using void * as an intermediate type in a "chained" cast

    int *pi;
    ...
    double *pd = static_cast(static_cast(pi));
    

    const_cast cannot break strict aliasing in a compliant compiler.

    As for C99... What C99 did introduce was the restrict qualifier. This is directly related to aliasing, but it is not what is known as strict aliasing per se.

提交回复
热议问题