Given a void *
to some storage, how to check whether it points to properly aligned storage without any implementation defined behavior?
Of course we have std::align
, but is there a more effective way to do this?
template <std::size_t alignment>
inline bool is_aligned(void * ptr) noexcept {
std::size_t max = 1u;
return std::align(alignment, 1u, ptr, max);
}
PS: I need to do this in a C++ standards-compatible fashion, without relying on any platform-specific (implementation defined) hacks.
PPS: I apologize for my (comprehension of) English, its not my native language.
EDIT (2018.08.24): Removed "effective" from the title, added even more wording to emphasize that I don't want any implementation defined or platform-specific behavior.
std::intptr_t
is useful here). For example to check if a pointer is on an even address you could doreinterpret_cast<intptr_t>(some_pointer) & ~1
. – Steinbachptr
(in your example) is not itself aconstexpr
then neither can the result of any calculation using it beconstexpr
. – Steinbachnew
ornew[]
you can be certain that the memory should be well-aligned for the type you're working with. Perhaps you can enlighten us about the problem you are actually trying to solve by checking the alignment? Why do you need to check it? – SteinbachT
or whether one needs to usestd::memcpy
to copy the respective data from/to the buffer before/after accessing these as typeT
. – Prudhoestruct OveralignedInt { alignas(1024) int i; };
– Haymanchar
buffer) as someT
even when alignment requirements are met. You'll have to begin the lifetime of the object with placementnew
first. – Kreplachconstexpr
? – Nicknackchar
buffer, but just storage allocated by, say,::operator new(std::size_t)
? – Prudhoemalloc
. There is no object for you to access until you create it. – Kreplach