Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange use of constructor in C++

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?

like image 440
enc Avatar asked Jan 28 '16 12:01

enc


2 Answers

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.

like image 55
Niall Avatar answered Nov 01 '22 16:11

Niall


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

like image 2
Zegar Avatar answered Nov 01 '22 17:11

Zegar