Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use the __gc keyword on managed C++ classes?

I have a C++ project that I've successfully wrapped with .NET classes using C++/CLI. I'm defining the wrapper classes in managed C++. Do I need to mark the classes as __gc in order for the classes to be garbage collected? Or will the .NET framework automatically GC the classes since they are managed classes?

This is how its currently declared

public ref class Player {

Do I need something like this?

__gc class Player { .. }
like image 428
Robin Rodricks Avatar asked Feb 18 '23 01:02

Robin Rodricks


1 Answers

The keyword __gc was used in the previous version (IIRC, till VS2003). Then the new context-specific keywords (like ref class, value struct) were added. Newer compilers (VS2005+) would understand and suggest to use newer keywords. Context keyword ref class is enough to state that this class is a managed class. Managed classes can only be allocated using gcnew keyword. The compiler will raise an error of new is used for managed-classes. For VC++ (/clr), stack-semantics are also available.

That means the following is also valid:

public ref class SomeClass{};

void foo()
{
    SomeClass cls; // On stack!    
}
like image 187
Ajay Avatar answered Mar 05 '23 05:03

Ajay