What does "new (&variable) value;" in C++ do?

c++, new-operator, operators

Solution

It's called placement new. It calles the constructor on the specified memory rather than allocating new memory. Note that in this case you have to explicitly call the destructor of your object before freeing the allocated memory.

Clarification. Suppose you have allocated some raw memory

char * rawMemory = new char [sizeof (Object)];

and you want to construct an object on that memory. You call

new(rawMemory) Object(params);

Now, before freeing the memory

delete [] rawMemory; 

you will have to call the derstuctor of Object explicitly

reinterpret_cast<Object*>(rawMemory)->~Object();

In your particular example, however, the potential problem is that you haven't properly destroyed the existing object before constructing a new one in its memory.

Bonus: Ever wondered how standard `std::vector` can do without its contained objects being default-constructible? The reason is that on most, if not all, implementations `allocator<T>` does not store a `T* p` which would require T to be default-constructible in case of `p = new T[N]`. Instead it stores a `char` pointer - raw memory, and allocates `p = new char[N*sizeof(T)]`. When you `push_back` an object, it just calls the copy constructor with placement new on the appropriate address in that char array.

Problem

Say I have the following code in a C++ program: ``` Object a = Object(someParameters); new (&a) Object(someOtherParameters); ``` My assumption is that it replaces the contents of `a` with `Object(someOtherParameters)`, avoiding a possible `operator=` declared for `Object`. Is this correct?

Original source