Re: exceptions
On Sep 17, 5:47 pm, "Alf P. Steinbach" <al...@start.no> wrote:
* dragonslayer...@hotmail.com:
If you have code like:
try
{
c = 0; // initialize
c = new C(...); // c of type C*
}
catch( E& e)
{
...
}
and an exception is thrown inside the constructor. Is it guaranteed
that c will be null?
Yes.
Are you sure? It's what I would expect, and it might be the
intent of the standard, but I don't think that the standard
actually guarantees it anywhere. I can't find anything in the
standard which guarantees that the pointer will not be modified
until after the return from the constructor; formally, at least,
a compiler could break the statement with the new down into:
c = operator new( sizeof( C ) ) ;
c->C() ; // Call the constructor.
(Note that if the constructor exits via an exception, the memory
will be freed. which would mean that c would end up containing
an invalid pointer.)
If this is important, the obvious solution is:
try {
c = 0 ;
C* tmp = new C(...) ;
c = tmp ;
// ...
} catch ( E& e ) {
// ...
}
If c is a smart pointer, the original code should also work,
since the assignment operator is actually a function call, and
thus introduces a sequence point.
--
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