Search code examples
c++c++11pointersdynamic-memory-allocationreinterpret-cast

casting char-array into array of PODs in C++


What's the correct way to write the code below?

I have a memory manager which provides me with char *'s, but I need to work with arrays of uint32_t. How can I work around the strict aliasing rule? I understand that with a single object it's advised just to copy the contents with memcpy() but that solution is not acceptable for an array of objects.

char* ptr = manager()->Allocate(1000 * sizeof(uint32_));
uint32_t* u32ptr = reinterpret_cast<uint32_t*>(ptr);
....
u32ptr[x] = y;

Solution

  • You can use placement-new:

    uint32_t* u32ptr = new(ptr) uint32_t[1000];
    

    Note that after this, the effective type of the storage is uint32_t, and you may not use ptr any more. You don't have to do anything special with the chars, because for types with a trivial destructor, you can end their lifetime simply by reusing the storage.