4

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Geo Paul
  • 1,777
  • 6
  • 25
  • 50
  • That looks like a bitwise exclusive OR to me. Can you show more context for where you saw this? – merlin2011 Apr 29 '14 at 05:19
  • 2
    This is a thing from Microsoft's "Managed C++" (which is a sort of hybrid between C++ and C#). I believe they no longer encourage its use, preferring you to use C#. – M.M Apr 29 '14 at 05:20
  • 1
    Possible duplicate : http://stackoverflow.com/questions/202463/what-does-the-caret-mean-in-c-cli – gaganbm Apr 29 '14 at 05:21
  • This article explains it in some more detail: http://www.i-programmer.info/programming/cc/921-getting-started-with-managed-c.html – User Apr 29 '14 at 05:22

2 Answers2

3

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();   
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

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.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174