Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 801
MrMage Avatar asked Nov 29 '12 13:11

MrMage


People also ask

What is adjectives of new?

adjective. /nu/ (newer, newest) not existing before. not existing before; recently made, invented, introduced, etc.


2 Answers

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.

like image 75
Armen Tsirunyan Avatar answered Oct 09 '22 06:10

Armen Tsirunyan


It's known as placement new: it constructs the new Object at the address given inside the parentheses. Placement new is usually used to create an object in raw memory. Constructing a new object on top of an existing one, as this code does, is a bad idea, because it doesn't call the destructor on the original object.

like image 28
Pete Becker Avatar answered Oct 09 '22 05:10

Pete Becker