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.
I'm not sure what the question here is. "What do you think?" I think ptrdiff_t is indeed the correct datatype to represent the difference between two pointers, but it makes very little sense to compare two pointers if they are not pointing into a block of contiguous memory that comes from a simple allocation (and as a corollary, neither of the two pointers being compared should ever be NULL).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With