Re: Code getting Crashed( C++)
On Aug 7, 1:00 pm, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2008-08-07 11:39, Pallav singh wrote:
std::auto_ptr<Pizza> CreateNew_PizzaProduct()
{ pizza.reset(new Pizza()); }
Actually I'm surprised your code crashes, because it should
not even compile. In the above function you forgot to return a
value.
Which is undefined behavior, and doesn't require a diagnostic.
It would be nice if the compiler issued a warning, but the code
is perfectly legal if a) the function is never actually called,
or b) the expression "new Pizza()" always threw an exception, or
failed to return normally for some other reason.
This is even useful, in some admittedly rare cases, e.g.:
SomeType
Derived::f()
{
// The base class imposes pre-conditions which can
// never be met in this derived class, so...
assert( 0, "pre-conditions not met" ) ;
abort() ;
}
It might be possible (though it should not happen) that your
compiler returns some default value which is somehow converted
to std::auto_ptr<Pizza> which causes a crash when
CreateNew_PizzaProduct is called in ConstructPizza.
More likely, his compiler supposes that no code flow will ever
result in falling off the end, and doesn't do anything. So the
calling code ends up using uninitialized memory as an auto_ptr.
(Note that even if the calling code doesn't use the return value
explicitly, it will call the destructor on it.)
--
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