user3215269
user3215269

Reputation: 21

Strict Aliasing how resolve?

inline void addHeader(T value)
{
    if(sizeof(T) > m_outputBufferStart)
    {
        std::clog << "[Error - OutputMessage::addHeader] m_outputBufferStart(" << m_outputBufferStart << ") < " << sizeof(T) << std::endl;
        return;
    }

    m_outputBufferStart -= sizeof(T);
    *(T*)(m_buffer + m_outputBufferStart) = value; //here is error
    m_size += sizeof(T); //current size of buffer
}

my question is how can I solve strict aliasing? I don't want to "skip" this warning,

buffer is array of uint8_t

Upvotes: 2

Views: 93

Answers (1)

typ1232
typ1232

Reputation: 5607

The warning can be silenced by casting the array value to an integer for doing the pointer arithmetic.

*(T*)((uintptr_t)m_buffer + m_outputBufferStart) = value;

A more C++y way would probably be to cast the type to a pointer and then copying it to the buffer.

std::copy_n(&m_buffer[m_outputBufferStart], sizeof(T), (uint8_t*)value);

Upvotes: 1

Related Questions