Question

I was reading some code in cpp and I found some code like

<classname>^ instancename

. what is its use??

I tried searching but did not get any answers.

Was it helpful?

Solution

It represents a managed pointer, ^ points to a garbage collected object (handled by the framework).

You can check this for more details

In Visual C++ 2002 and Visual C++ 2003, __gc * was used to declare a managed pointer. This is replaced with a ^ in Visual C++ 2005, for example ArrayList^ al = gcnew ArrayList();.

They are also allocated differently for example:

NativeObject* n = new NativeObject();
ManagedObject^ m = gcnew ManagedObject();

Also check this MSDN for more details

This sample shows how to create an instance of a reference type on the managed heap. This sample also shows that you can initialize one handle with another, resulting in two references to same object on managed, garbage-collected heap. Notice that assigning nullptr (C++ Component Extensions) to one handle does not mark the object for garbage collection.

// mcppv2_handle.cpp
// compile with: /clr
ref class MyClass {
public:
   MyClass() : i(){}
   int i;
   void Test() {
      i++;
      System::Console::WriteLine(i);
   }
};

int main() {
   MyClass ^ p_MyClass = gcnew MyClass;
   p_MyClass->Test();

   MyClass ^ p_MyClass2;
   p_MyClass2 = p_MyClass;

   p_MyClass = nullptr;
   p_MyClass2->Test();   
}

OTHER TIPS

The handle declarator (^, pronounced "hat", C++/CLI terminology), modifies the type specifier to mean that the declared object should be automatically deleted when the system determines that the object is no longer accessible.

A variable that is declared with the handle declarator behaves like a pointer to the object. However, the variable points to the entire object, cannot point to a member of the object, and it does not support pointer arithmetic. Use the indirection operator (*) to access the object, and the arrow member-access operator (->) to access a member of the object.

Check out here and this thread for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top