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?
adjective. /nu/ (newer, newest) not existing before. not existing before; recently made, invented, introduced, etc.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With