Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placement new and alignment in C++

Tags:

c++

c++11

Consider the following code snippet constructing an instance of a POD (plain old data) struct in-place:

#include <new>
#include <cassert>
#include <cstddef>

struct Test
{
    int a;
    char b;
    double c;
};

int main()
{
    const std::size_t minimumNumberOfBytes = sizeof( Test ) * 4;

    // Get a block of memory that can accommodate a Test instance and then some!
    void* const ptrToMemBlock = new char[ minimumNumberOfBytes ];
    assert( ptrToMemBlock );

    // Construct a Test instance in-place.
    const Test* const testInstance( ::new ( ptrToMemBlock ) Test() );

    // Is this assumption guaranteed to be true?
    assert( testInstance == ptrToMemBlock );
}

Is the assumption represented by the final assert() guaranteed to always be correct? Or is it conceivable that the compiler might decide to construct the Test instance, say a few bytes after the start of the memory block I specified in the placement-new call?

Note that I'm asking specifically about POD types here. I know that things can get iffy if multiple inheritance and stuff like that gets involved.

like image 563
antred Avatar asked Oct 28 '14 17:10

antred


1 Answers

This assertion will always hold, because new is required to return blocks of memory with MAXIMUM possible alignment. BTW - your first assert() is worthless, as normal new does not return nullptr - it throws or aborts, only "nothrow new" can return nullptr.

like image 88
Freddie Chopin Avatar answered Sep 21 '22 21:09

Freddie Chopin