How to use the new syntax

When I read the article, I found that this line is so mysterious.

new (new_ptr + i) T(std::move(old_ptr[i])); 

Can someone explain how this syntax works?

+4
source share
2 answers

Its placement.

 new (new_ptr + i) T(std::move(old_ptr[i])); 

Here we can simplify this:

 new (<destinationLocation>) T(<constructor parameters); 

This is normal C ++ 03 and basically allows you to dynamically create an object in the memory area that you previously allocated (its an advanced technique that most people will not use (unless they create their own container, such as objects)).

The std :: move () part is from C ++ 11 and creates a special reference type that allows you to use the move constructor in type T.

 new T(std::move(<source Obj>)); 

This basically means creating a new T using the original object and using the move constructor for efficiency. This means that the "original Obj object" will remain in the undefined state (therefore, not used) after moving, but it allows you to efficiently create objects.

Combining the two, you get a new location with a move, using an element from the array as the source object.

+6
source

Well, the good news: none of them is the new syntax (but all this is the syntax new , ho ho!). There is a function that was introduced in C ++ 11, std::move , but what is it.

The string syntax is known as placing new and has been around for a good time. This allows you to create an object on some already allocated space in memory. Here, the memory already allocated is indicated by the pointer new_ptr + i . Type of object to be created: T

A simple and meaningless example of placing 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 T is passed to std::move(old_ptr[i]) . Assuming old_ptr points to objects of type T , this step allows you to use the move constructor T to create the object. It basically pretends that old_ptr[i] is a temporary object of T (even if it may not be), allowing the new T to steal it. To learn more about this, find move semantics .

+12
source

All Articles