Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange C++ new operator usage [duplicate]

While digging in a C++ project, I encountered a strange usage of C++'s new operator:

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

Would you please help me understand this syntax?

like image 692
dvnguyen Avatar asked Nov 04 '13 11:11

dvnguyen


3 Answers

It's the placement new syntax - it allows you to construct an object at the pointed-to location in memory. Consider a "normal" use of 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 hold an X (without constructing an X in it), then explicitly constructs an X in the allocated memory. Later, it explicitly destructs the X it created and then deallocates the memory that contained it.

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

like image 191
Stuart Golodetz Avatar answered Sep 19 '22 11:09

Stuart Golodetz


This syntax is called the placement new syntax. It is typically used to construct an object on a pre-allocated buffer. This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there's no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-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 deallocation, there is no placement delete that automatically does the magic. You should not deallocate every object that is using the memory buffer. Instead you should destruct each object manually, then delete[] only the original buffer

like image 44
jester Avatar answered Sep 19 '22 11:09

jester


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

In the case you cited it is using the pointer for arr to create its new instance of ClassA in.

like image 29
GMasucci Avatar answered Sep 20 '22 11:09

GMasucci