Can anyone explain me why using specifier alignas
it is not possible to create buffer on stack which contains 2 bytes and aligned strictly by specified alignment(not more and not less)?
To be clear what I mean here is code snippet:
#include <cassert>
#include <cstddef>
#include <cstdint>
int main()
{
// create buffer on stack which contains 2 bytes and aligned by boundary of 1 byte
alignas(1) std::byte buf[2]{};
// convert pointer to first byte in the buffer to unsigned integer
const auto buf_ptr_as_uint = reinterpret_cast<std::uintptr_t>(buf);
// expect that address of first byte in the buf aligned by boundary of 1 byte(not 2)
// namely I expect that last bit of buf_ptr_as_uint should be equal to 1
// but this is not true. assert is always being triggered.
assert((buf_ptr_as_uint & 1));
}
I understand that any address which is aligned by boundary of 2 bytes is already aligned by boundary of 1 byte. But even so I was expecting that "alignas" should align my buffer exactly according to the specified alignment especially considering that requirement for alignment of std::byte
should allow to satisfy my will to align buf
strictly by 1 byte boundary.
So my question is: why alignas
works in this way? And is there a way to force compiler to align my buffer strictly by specified alignment(besides allocating bigger buffer and skipping bytes inside it)? Or am I missing something?
alignas
only specifies that the object's address must be aligned at least as strict as it specifies.
why alignas works in this way?
Because the point of alignas
is to make sure that the buffer/storage is usable to place objects there which have certain alignment requirements. For that it doesn't matter whether the buffer is also aligned for other types with higher alignment requirement (and even if it did, usually you'd want to have your memory be aligned for more, not less, types).
What is the point of intentionally misaligning for types that have a higher alignment requirement as stated in the alignas
specifier and likely forcing the compiler to waste space in the process? I do not see any use case.
And is there a way to force compiler to align my buffer strictly by specified alignment(besides allocating bigger buffer and skipping bytes inside it)?
There isn't. What you suggest is the way to do it. The compiler couldn't implement it any other way either.