reinterpret_cast and explicit alignment requirement

  alignment, c++, reinterpret-cast

Given this (bold part) about reinterpret_cast, I was expecting that the piece of code below would generate different addresses when casting X* to Y* since the latter is more striclty aligned than the former. What am I missing here?

Any object pointer type T1* can be converted to another object pointer type cv T2*. This is exactly equivalent to static_cast<cv T2*>(static_cast<cv void*>(expression)) (which implies that if T2’s alignment requirement is not stricter than T1’s, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value)

cppreference/reinterpret_cast

#include <iostream>


struct alignas (1) X
{
    char c;
};


struct  alignas (32) Y
{
    char c;
};

int main(int argc, const char *const* const argv)
{
    std::cout << alignof(X) << " " << alignof(Y) << std::endl;

    X x;
    Y y;
    std::cout << &x << " " << reinterpret_cast<Y*>(&x) << std::endl;
    std::cout << &y << " " << reinterpret_cast<X*>(&y) << std::endl;

}

output

Program returned: 0
1 32
0x7ffef3434578 0x7ffef3434578
0x7ffef3434540 0x7ffef3434540

snippet on godbolt

Source: Windows Questions C++

LEAVE A COMMENT