When I am reading some article i found this line is so cryptic.
new (new_ptr + i) T(std::move(old_ptr[i]));
Can somebody explains how this syntax works?
When I am reading some article i found this line is so cryptic.
new (new_ptr + i) T(std::move(old_ptr[i]));
Can somebody explains how this syntax works?
Well, the good news is, none of it is new syntax (but all of it is new
syntax, ho ho!). There is a function being used that was introduced in C++11, std::move
, but that's it.
The syntax of the line is known as placement new
and has been around for a good while. It allows you to create an object at some already allocated space in memory. Here, the memory that is already allocated is given by the pointer new_ptr + i
. The type of the object being created there is a T
.
A simple and pointless example of placement new is:
int* p = new int(); // Allocate and initialise an int
new (p) int(); // Initialise a new int in the space allocated before
The constructor of T
is being passed std::move(old_ptr[i])
. Assuming old_ptr
points at objects of type T
, this move allows the move constructor of T
to be used to create the object. It basically pretends that old_ptr[i]
is a temporary T
object (even if it may not actually be), allowing the new T
to steal from it. To learn more about this, look up move semantics.
Its a placement.
new (new_ptr + i) T(std::move(old_ptr[i]));
Here we can simplify this to:
new (<destinationLocation>) T(<constructor parameters);
This is normall C++03 and basically allows you to create an object dynamically in an area of memory that you have pre-allocated (its an advanced technique that most people will not use (unless they are building their own container like objects)).
The std::move() part is from C++11 and is creating a special reference type that allowes the move constructor to be used in the type T.
new T(std::move(<source Obj>));
This basically says create a new T using the source object and use the move constructor for effeciency. This means the 'source Obj' will be left in an undefined state (thus not usable) after the move but it allows from efficient object creation.
Combining the two you get placement new with move construction using an element from an array as the source object.