Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

placement new and delete

What is the right method to delete all the memory allocated here?

  const char* charString = "Hello, World";   void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1);   Buffer* buf = new(mem) Buffer(strlen(charString));    delete (char*)buf; 

OR

  const char* charString = "Hello, World";   void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1);   Buffer* buf = new(mem) Buffer(strlen(charString));    delete buf; 

or are they both same?

like image 689
Vink Avatar asked Jul 21 '11 23:07

Vink


People also ask

Is there a placement delete?

Placement deleteIt is not possible to call any placement operator delete function using a delete expression. The placement delete functions are called from placement new expressions. In particular, they are called if the constructor of the object throws an exception.

What is placement new and why would I use it?

Placement new is a variation new operator in C++. Normal new operator does two things : (1) Allocates memory (2) Constructs an object in allocated memory. Placement new allows us to separate above two things. In placement new, we can pass a preallocated memory and construct an object in the passed memory.

Does placement new call destructor?

¶ Δ Probably not. Unless you used placement new , you should simply delete the object rather than explicitly calling the destructor.

How does new and delete work?

The deallocation counterpart of new is delete, which first calls the destructor (if any) on its argument and then returns the memory allocated by new back to the free store. Every call to new must be matched by a call to delete; failure to do so causes memory leaks.


1 Answers

The correct method is:

buf->~Buffer(); ::operator delete(mem); 

You can only delete with the delete operator what you received from the new operator. If you directly call the operator new function, you must also directly call the operator delete function, and must manually call the destructor as well.

like image 108
bdonlan Avatar answered Sep 24 '22 01:09

bdonlan