Chưa phân loại

C++/CLI Tutorial – How to monitor managed object in C++ program

Almost C++ programmer want to manage all object they created. But when they use gcnew in C++/CLI to create objects, it seems they were not able to control these objects and that makes them feel uncomfortable.

We can only set these object to nullptr and cannot delete it by calling delete, this is responsibility of GC. We can call GC.Collect to collect all objects that are no longer reference to.

In .NET, we have WeakReference class which allows us to monitor managed object to ensure that when we call GC.Collect, whether these object was deleted or not.

And here is source code to illustrate for what I said:

// Monitor managed object
#include <iostream>		// For cout

using namespace std;
using namespace System;	// For weak

ref class MyClass {
public:
	int k;
	MyClass() {
		k = 210;
	}
};

int main() {

	MyClass ^ h_MyClass = gcnew MyClass;

	// Create a WearReference object to monitor h_MyClass object
	WeakReference ^ weak = gcnew WeakReference(h_MyClass);

	// View h_MyClass info
	cout << "Address if h_MyClass: " << &h_MyClass << endl;
	cout << "Value of h_MyClass->k: " << h_MyClass->k << endl;

	// Set h_MyClass to NULL
	h_MyClass = nullptr;

	// Explicitly call GC.Collect
	GC::Collect(GC::MaxGeneration, GCCollectionMode::Forced);

	// Check whether h_MyClass was deleted or not
	if(weak->IsAlive) {
		cout << "h_MyClass was not deleted yet";
	}
	else {
		cout << "h_MyClass was deleted";
	}

	// Stop to see the result
	cin.get();
}

Happy coding!!

Advertisements

1 thought on “C++/CLI Tutorial – How to monitor managed object in C++ program”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s