[vtk-developers] Calling foo->Delete() automatically.

Brad King brad.king at kitware.com
Wed May 15 16:53:24 EDT 2002

Hello, all:

Recently I've been switching often between developing VTK classes and
developing projects that use smart pointers.  As a result, I've
created many leaks by forgetting to add "foo->Delete()" at all exit
points of a method.

One intention of C++'s automatic variable destruction feature is for
resource cleanup.  I propose the following short class for inclusion
in vtkSetGet or another high-level header:

class vtkAutoDelete
  vtkAutoDelete(vtkObject* obj): Object(obj) {}
  ~vtkAutoDelete() { if(this->Object) { this->Object->Delete(); } }
  vtkObject* Object;

An instance of this class exists only to call Delete() on an object at
all exit points in a method that owns a reference to that object.
Here is an example use:

  vtkFoo* foo = vtkFoo::New();
  vtkAutoDelete delete_foo(foo);
  ... setup foo ...
    return 0; // foo automatically deleted.
  ... use foo ...
    return 0; // foo automatically deleted.
  return 1; // foo automatically deleted.

This idea is similar to smart pointers, but it is completely optional and
requires no changes to existing code.  It is really a VTK version of the
C++ standard's "auto_ptr" class.

I'm interested in the list's comments.


More information about the vtk-developers mailing list