Using the new Strange C ++ operator

While digging in a C ++ project, I came across a strange use of the C ++ operator new :

 int arr[5]; ClassA* a = new(arr) ClassA(); 

Could you help me understand this syntax?

+6
source share
3 answers

This is a new placement syntax - it allows you to build an object at a specified location in memory. Consider the "normal" use of the new:

 X *p = new X; ... delete p; 

You can achieve the same effect by doing:

 #include <new> ... void *buffer = ::operator new(sizeof(X)); X *p = new (buffer) X; ... p->~X(); ::operator delete(buffer); 

The latter allocates enough memory to store X (without creating X in it), and then explicitly creates X in the allocated memory. Later, it explicitly destroys the created X and then frees the memory containing it.

See also the C ++ FAQ: http://www.parashift.com/c++-faq/placement-new.html

+2
source

The new() operator can take size (size in bytes) nothrow_value (returns a null pointer instead of a bad_alloc exception) or pointer (build an object in the memory already allocated, which this pointer points to), and in the description that you describe, a new object is created in the memory location pointed to by arr . For a decent guide on it, I would look at this link .

In the case you pointed out, use the pointer for arr to create your new ClassA instance in.

+2
source

This syntax is called the placement new syntax. It is usually used to construct an object in a pre-allocated buffer. This is useful when creating a memory pool, garbage collector, or simply when safety of performance and exceptions is paramount (there is no danger of distribution failure, because memory is already allocated, and building an object in a previously allocated buffer takes less time).

 char *buf = new char[sizeof(string)]; // pre-allocated buffer string *s1 = new (buf) string("test1"); // placement new string *s2 = new string("test2"); //ordinary new 

When it comes to liberation, there is no placement delete that automatically does the magic. You do not have to free all objects that use the memory buffer. Instead, you must destroy each object manually, and then delete [] only the source buffer

+2
source

Source: https://habr.com/ru/post/957330/


All Articles