Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling delete on the result of a placement delete which used operator new okay?

If I do

struct MyStruct { ~MyStruct() { } };

void *buffer = operator new(1024);
MyStruct *p = new(buffer) MyStruct();
// ...
delete p;     //    <---------- is this okay?

is the delete guaranteed to take care of both calling ~MyStruct() as well as operator delete?

like image 611
user541686 Avatar asked May 23 '13 23:05

user541686


1 Answers

delete p is equivalent to

p->~MyStruct();
operator delete(p);

unless MyStruct has an alternative operator delete, so your example should be well-defined with the expected semantics.

[expr.delete]/2 states:

the value of the operand of delete may be ... a pointer to a non-array object created by a previous new-expression.

Placement new is a type of new-expression. [expr.new]/1:

new-expression:
    ::opt new new-placementopt new-type-id new-initializeropt
    ::opt new new-placementopt ( type-id ) new-initializeropt

delete is defined to be a call to the destructor of the object and then a call to the deallocation function for the memory. [expr.delete]/6,7:

... the delete-expression will invoke the destructor (if any) for the object ...

... the delete-expression will call a deallocation function ...

As long as the deallocation function matches the allocation function (which it should, as long as you haven't overloaded operator delete for your class), then this should all be well defined.

like image 142
Mankarse Avatar answered Sep 30 '22 16:09

Mankarse