Re: explicit call of constructor and destructor
On Dec 4, 4:47 am, Abhishek Padmanabh <abhishek.padman...@gmail.com>
wrote:
[...]
This is crucial, because the
constructor might throw an exception. The placement new expression sets=
up an exception handler first of all, which has responsibility for
deallocation, before it calls the constructor for you -- the explicit
syntactical constructor call in the expression is, at the level of
execution, a wrapped call.
Sorry, this is new to me. How could the handler be set up by
the placement new call?
There are four different ways the compiler can generate code for
a new expression, depending on whether there is a corresponding
(placement) delete, and whether the operator new function is
declared not to throw or not. Basically (for p = new T):
corresponding delete, operator new() may throw:
T* tmp = operator new( sizeof(T) /* , any placement params.
*/ ) ;
try {
T::constructor( tmp ) ;
} catch ( ... ) {
operator delete( tmp /* , any placement params. */ ) ;
throw ;
}
corresponding delete, operator new declared with throw()
T* tmp = operator new( sizeof(T) /* , any placement params.
*/ ) ;
if ( tmp != NULL ) {
try {
T::constructor( tmp ) ;
} catch ( ... ) {
operator delete( tmp /* , any placement params. */ ) ;
throw ;
}
}
no corresponding delete, operator new() may throw:
T* tmp = operator new( sizeof(T) /* , any placement params.
*/ ) ;
T::constructor( tmp ) ;
no corresponding delete, operator new declared with throw()
T* tmp = operator new( sizeof(T) /* , any placement params.
*/ ) ;
if ( tmp != NULL ) {
T::constructor( tmp ) ;
}
As you can see, if there is a corresponding operator delete, the
compiler must call it if the constructor terminates with an
exception.
Note that except for the case of a placement new expression with
no corresponding delete or a local static variable, the compiler
always frees the memory allocated for the variable being
constructed. Except in new expressions, however, this all
happens behind the scenes, where you cannot get at it to
instrument. (While I've shown this as try blocks in the above,
it's more likely that the compiler uses the same mechanism it
uses to call destructors of local variables in practice.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34