Recently I found the following while reviewing some old code:
auto_ptr<DerivedClass> pointer = dynamic_cast<CBase*>( new CDerived() );
aside from the fact that this code is meaningless in valid cases (in valid cases class Derived
is derived from class Base
and no dynamic_cast
is necessary) there's a problem with object ownership. If for whatever reason dynamic_cast
returns a null pointer the auto_ptr
will not be bound to the created object and the object will be leaked.
Is there some technique to help prevent such errors like making a compiler issue a warning or anything like that?