Visual C++ .NET/Class/Destructor
Destructor and finalizer
#include "stdafx.h"
using namespace System;
using namespace System::Collections::Generic;
ref class MyClass{
static List<MyClass^>^ instanceTrackingList;
static MyClas(){
instanceTrackingList = gcnew List<MyClass^>;
}
MyClass(String^ s)
{
Label = s;
instanceTrackingList->Add( this );
}
property String^ Label;
static int EnumerateInstances()
{
int i = 0;
for each (MyClass^ r in instanceTrackingList)
{
i++;
Console::WriteLine( r->Label );
}
return i;
}
~MyClass() // destructor
{
this->!MyClass();
}
!MyClass() // finalizer
{
instanceTrackingList->Remove( this );
}
};
int main(){
MyClass r1("ABC");
MyClass^ r2 = gcnew MyClass("XYZ");
int count = MyClass::EnumerateInstances();
Console::WriteLine("Object count: " + count);
delete r2;
count = MyClass::EnumerateInstances();
Console::WriteLine("Object count: " + count);
}
Destructor demo
#include "stdafx.h"
using namespace System;
using namespace System::IO;
ref class MyClass
{
public:
MyClass()
{
Closed = false;
}
~MyClass()
{
if ( !Closed ) Close();
}
void Close()
{
// Release unmanaged resources
Closed = true;
}
private:
bool Closed;
};
void main()
{
MyClass^ myObject = gcnew MyClass();
try
{
// Do something
}
finally
{
// Calls destructor
delete myObject;
}
}
Destructors and inheritance
#include "stdafx.h"
using namespace System;
ref class Base
{
public:
Base() {}
~Base() { Console::WriteLine("~Base"); }
};
ref class Derived : Base
{
public:
Derived() { }
~Derived() { Console::WriteLine("~Derived"); }
};
// The destructor will be called at the end of main.
int main()
{
Derived d;
}