Listing 3: Three techniques for dealing with destructors
// $Id$ #include <gc_cpp.h> #include <iostream> using std::cout; using std::endl; class ManualDelete : public virtual gc { public: static long constructors; static long destructors; virtual ~ManualDelete () { ++destructors; }; ManualDelete () { ++constructors; }; }; long ManualDelete::constructors = 0; long ManualDelete::destructors = 0; class AutoDelete : public virtual gc_cleanup { public: static long constructors; static long destructors; virtual ~AutoDelete () { ++destructors; }; AutoDelete () { ++constructors; }; }; long AutoDelete::constructors = 0; long AutoDelete::destructors = 0; int main () { for (long i = 0; i < 500000; ++i) { ManualDelete md_on_stack; AutoDelete ad_on_stack; int *i = new (UseGC) int; char *array = new (UseGC) char[4 * 1024]; ManualDelete *md = new ManualDelete; AutoDelete *ad = new AutoDelete; // int and char[] don't have destructors, so mustn't delete. // Must delete the ManualDelete. // Boehm will delete the AutoDelete. delete md; } AutoDelete *ad2 = new AutoDelete; delete ad2; cout << "ManualDelete constructors " << ManualDelete::constructors << ", destructors " << ManualDelete::destructors << endl << "AutoDelete constructors " << AutoDelete::constructors << ", destructors " << AutoDelete::destructors << endl; return 0; }