9
I want to perform check for memory alignment of some type T. The straightforward way to do this is
if (((uintptr_t)&var & __alignof(T) - 1) == 0) ...
however, uintptr_t is not part of existing C++ standard and it is not supported by some compilers, so I'm looking for a portable alternative way to do this and std::ptrdiff_t looks good for me. std::ptrdiff_t guaranteed to be able to store difference between two pointers, but who says that one of those pointers cannot be null pointer? In that case std::ptrdiff_t has to be at least same size as the pointer itself.
template <typename T> bool is_properly_aligned(const T* const ptr)
{
std::ptrdiff_t diff = (ptr - static_cast<T*>(0)) * sizeof(T);
return ((diff & __alignof(T) - 1) == 0);
}
or like that (to get rid of multiplication by sizeof(T))
template <typename T> bool is_properly_aligned(const T* const ptr)
{
std::ptrdiff_t diff =
reinterpret_cast<const char*>(ptr) - static_cast<const char*>(0);
return ((diff & __alignof(T) - 1) == 0);
}
What do you think about such kind of solution? Is it portable enough? I don't see any reasons why this should fail, however I would like to confirm.
Thanks.