c++c++14memory-alignment

Can I use std::align to verify the alignment of a given pointer?


The following function template tries to locate an object in an array of bytes. We may assume that the argument buffer "usually" holds an object of the given type, but I need a diagnostic (assertion check) against possible errors.

template <typename T>
T* get_object_from_buffer(std::uint8_t* buffer, std::size_t size)
{
    // EDIT: This constraint was missing in original version of the question.
    if (size != sizeof(T))
    {
        // Invalid usage of the function.
        return nullptr;
    }
    
    void* tmp_buffer = buffer;
    if (nullptr != std::align( alignof(T),
                               sizeof(T),
                               tmp_buffer,
                               size ) )
    {
        return reinterpret_cast<T*>(buffer);
    }
    else
    {
        // Caller can check returned pointer to implement diagnostic reactions
        return nullptr;
    }
}

Questions:

  1. Is it allowed (and portable) to do this using std::align?

  2. Do you see a better solution - more robust, more elegant?

Conditions:


Edit/Update: The buffer representation of uint8_t* and size_t is only meant to hold a single T object. This was missing in the original question post. I have added the check that the size argument actually matches the size of the object.

Without this check, std::align() can easily locate an aligned T* in buffer so that the criterion is not relevant any more. Thanks to Ted Lyngmo for pointing this out!


Solution

  • Answer motivated by comments of @Ted Lyngmo - see comments to question