Strange use of constructor in C ++

I am trying to understand another person's code written in C ++, but there is a strange use of a constructor that I have never seen. The code is as follows:

A* a = new A(some initial values...); ... B* b = new (a) B(some initial values...); 

When initializing the variable b there is (a) between new and B(...) . What does it mean?

+5
source share
3 answers

Line of code:

 B* b = new (a) B(some initial values...); 

Uses "post new" .

Default behavior; it creates a new object of type B in the same memory location as object a . If there are associated overloads for the new placement, then the behavior will be the same as in the case of overload, which may also include the default behavior of the type.

The code must be taken into account for any overloads , the memory layout of objects, and how classes a and B relate to each other.

It is unusual to create an object above the location of a previously created object. I would suggest that there is some code between the two that deconstructs (but still leaves the allocated memory) the previous object a before building a new one in its place.

The isocpp FAQ contains additional tips for using this technique and its dangers.

+7
source

This is the so-called new placement syntax.

You may not understand this, but the new one behaves basically like a standard C ++ function and, therefore, can be overridden, and sometimes it can also take additional parameters. In this case, an additional parameter (argument) passed to the new function of class B is equal to a .

You can read more about it, for example here

+2
source

new expression

Without overload (in this case, it can even format your hard drive), this means constructing B at location a , without allocating new memory for itself.

0
source

Source: https://habr.com/ru/post/1241712/


All Articles