enc
enc

Reputation: 3415

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?

Upvotes: 6

Views: 265

Answers (3)

Niall
Niall

Reputation: 30606

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.

Upvotes: 7

Yam Marcovic
Yam Marcovic

Reputation: 8141

new expression

Unless overloaded (in which case it could even format your hard drive), it means construct B at location a, without allocating new memory for its own sake.

Upvotes: 0

Zegar
Zegar

Reputation: 1015

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

Upvotes: 2

Related Questions