Placement Syntax - Placement Delete

Placement Delete

As noted above, there is no placement delete expression. It 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. In such a circumstance, in order to ensure that the program does not incur a memory leak, the placement delete functions are called. A placement new expression first calls the placement operator new function, then calls the constructor of the object upon the raw storage returned from the allocator function. If the constructor throws an exception, it is necessary to deallocate that storage before propagating the exception back to the code that executed the placement new expression, and that is the purpose of the placement delete functions.

The placement delete function that is called matches the placement new function that was invoked by the placement new expression. So, for example, if the following code is executed, the placement delete function that is called will be operator delete(void *, const A &):

#include
#include

struct A {} ;
struct E {} ;

class T {
public:
T { throw E ; }
} ;

void * operator new ( std::size_t, const A & )
{std::cout << "Placement new called." << std::endl;}
void operator delete ( void *, const A & )
{std::cout << "Placement delete called." << std::endl;}

int main
{
A a ;
try {
T * p = new (a) T ;
} catch (E exp) {std::cout << "Exception caught." << std::endl;}
return 0 ;
}

This is why the pointer placement delete functions are defined as no-operations by the Standard C++ library. Since the pointer placement new functions do not allocate any storage, there is no storage to be deallocated in the event of the object's constructor throwing an exception.

If no matching placement delete function exists, no deallocation function is called in the event of an exception being thrown by a constructor within a placement new expression. There are also some (older) C++ implementations that do not support placement delete (which, like the exception-throwing allocator functions, were an addition made to C++ when it was standardized) at all. In both such situations, an exception being thrown by a constructor when allocating using a custom allocator will result in a memory leak. (In the case of the older C++ implementations, a memory leak will also occur with non-placement new expressions.)

Read more about this topic:  Placement Syntax

Famous quotes containing the word delete:

    Generalization, especially risky generalization, is one of the chief methods by which knowledge proceeds... Safe generalizations are usually rather boring. Delete that “usually rather.” Safe generalizations are quite boring.
    Joseph Epstein (b. 1937)