I'm trying to understand other person's code written in C++, but there is a strange use of constructor I've never seen. The code looks like this:
A* a = new A(some initial values...);
...
B* b = new (a) B(some initial values...);
When initializing variable b
there is (a)
between new
and B(...)
. What does this mean?
The line of code:
B* b = new (a) B(some initial values...);
Is using a "placement new".
The default behavior; it is creating the new object of type B
in the same memory location as the object a
. If there are associated overloads for the placement new, then the behavior would be as coded in the overload, which could include some default type behavior as well.
The code needs to be considered with any overloads, memory layout of the objects and how the classes A
and B
relate to each other.
It is unusual to create an object over the location of a previously created object. I would imagine there is some code between these two presented here that deconstructs (but still leaves the memory "allocated") the previous object a
before constructing the new one in its place.
The isocpp FAQ has some further advice on the use of this technique and its dangers.
This is so called placement new syntax.
Maybe you do not realize this but new behaves mostly as a standard C++ function and thus can be overridden and sometimes may also accept additional parameters. In this case, additional parameter (argument) being passed to the function new
of class B
is a
.
You can read more on this for example here
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