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.
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