1

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?

sharptooth
  • 167,383
  • 100
  • 513
  • 979

2 Answers2

3

Get rid of all your dynamic_casts.

All of them.

Then no tracking will be necessary.

Ben
  • 34,935
  • 6
  • 74
  • 113
1

If you can't find anything already available you can also add your own rule to cpp check

rve
  • 5,897
  • 3
  • 40
  • 64