Is it a strict aliasing violation to alias a struct as its first member?

后端 未结 3 1651
你的背包
你的背包 2020-12-09 09:00

Sample code:

struct S { int x; };

int func()
{
     S s{2};
     return (int &)s;    // Equivalent to *reinterpret_cast(&s)
}
         


        
3条回答
  •  温柔的废话
    2020-12-09 09:10

    I think it's in expr.reinterpret.cast#11

    A glvalue expression of type T1, designating an object x, can be cast to the type “reference to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_­cast. The result is that of *reinterpret_­cast(p) where p is a pointer to x of type “pointer to T1”. No temporary is created, no copy is made, and no constructors or conversion functions are called [1].

    [1] This is sometimes referred to as a type pun when the result refers to the same object as the source glvalue

    Supporting @M.M's answer about pointer-incovertible:

    from cppreference:

    Assuming that alignment requirements are met, a reinterpret_cast does not change the value of a pointer outside of a few limited cases dealing with pointer-interconvertible objects:

    struct S { int a; } s;
    
    
    int* p = reinterpret_cast(&s); // value of p is "pointer to s.a" because s.a
                                         // and s are pointer-interconvertible
    *p = 2; // s.a is also 2
    

    versus

    struct S { int a; };
    
    S s{2};
    int i = (int &)s;    // Equivalent to *reinterpret_cast(&s)
                         // i doesn't change S.a;
    

提交回复
热议问题