C++ "placement new" intricacies

924 views Asked by At

I've been reading some questions about placement new on SO and I am finding some different ways to use it that I thought I would ask about here. I understand that placement new is basically a way for you to create an object and give it a certain place in memory of your choice that has already been allocated; I just don't understand all of the intricacies.

First one I saw on SO uses this example (from C++ Primer):

const int BUF = 512;
const int N = 5;
char buffer[BUF];
double * pd1;
pd1 = new (buffer) double[N];

Second one I saw on SO uses this example (from C++ Primer Plus):

char * buffer = new char[BUF];   //get a block of memory
JustTesting *pc1, *pc2;

pc1 = new (buffer) JustTesting;  //Place object in buffer

The main difference between these two is that in the first block of code, buffer is a char array and in the second example it is a pointer to a char array, yet both blocks of code contain new (buffer).

My first question is: When using placement new in this context, can it accept either an object or it's address, and if so, is one preferred?

I've also seen placement new used without an lvalue. See below.

new(&myObject) myClass;

My second question is: What are the differences between placement new with vs. without an lvalue?

2

There are 2 answers

5
Maxim Egorushkin On BEST ANSWER

I understand that placement new is basically a way for you to create an object and give it a certain place in memory of your choice that has already been allocated;

Not exactly.

new expression calls the corresponding operator new and then invokes the constructor. Note that these are two different things named similarly.

Placement new expression skips allocating memory and only invokes the constructor. This is achieved by using the placement void* operator new( std::size_t count, void* ptr), which does nothing and returns ptr.

It is your job to provide storage for the object being initialized when using placement new.

0
Amit Rastogi On

Your first question is already answered. For your 2nd question - What are the differences between placement new with vs. without an lvalue?

Since placement new returns the address that is passed in its 2nd parameter, requiring an lvalue to store that address is optional. See the placement new implementation below from Microsoft Visual Studio-

inline void *__CRTDECL operator new(size_t, void *_Where) _THROW0()
    {   // construct array with placement at _Where
    return (_Where);
    }