Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use new syntax [closed]

Tags:

c++

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?

like image 953
K.K Avatar asked Dec 01 '22 20:12

K.K


1 Answers

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.

like image 102
Joseph Mansfield Avatar answered Dec 04 '22 08:12

Joseph Mansfield