This documentation is archived and is not being maintained.

4.3 Implementation of Destructors via Finalize

Visual Studio .NET 2003

Finalize is a method that is called on an object before it is deleted by the runtime garbage collector. This process is referred to as finalization. It takes place on a separate thread from execution. The execution order for Finalize calls in garbage-collected objects is unpredictable.

Destructors for __gc classes are implemented by the compiler renaming them to Finalize methods. The compiler injects code into each Finalize method to call any base object's Finalize. It also injects code to suppress any further finalization. The code is injected in the destructor because that is only called by delete, not the runtime garbage collector.

Example

This code:

// mcpp_destructors4.cpp
// compile with: /clr /LD
#using <mscorlib.dll>

__gc class A {
public:
   ~A() { System::Console::WriteLine(S"in ~A"); }
};
   
__gc class B : public A {
public:
   ~B() { }
};

is effectively transformed by the compiler to:

// do not compile
__gc class A {
public:
   A::Finalize() { Console::WriteLine(S"in ~A"); }

   virtual ~A() {
      System::GC::SuppressFinalize(this);
      A::Finalize();
   }
};

__gc class B : public A {
public:
   B::Finalize() { A::Finalize(); }

   virtual ~B() { 
      System::GC:SuppressFinalize(this);
      B::Finalize();
   }
};

Characteristic

  • A user-defined destructor of a __gc class is always virtual.

Constraints

  • Finalize cannot be defined by the user. It is a protected virtual member of System::Object.

    Example

    // mcpp_destructors5.cpp
    // compile with: /clr
    #using <mscorlib.dll>
    __gc class C {
    public:
       virtual void Finalize(); // C3840 can't define Finalize
    };
    
Show: