What does the caret (‘^’) mean in C++/CLI?

Viewed 110973

I just came across this code and a few Google searches turn up no explanation of this mysterious (to me) syntax.

Hashtable^ tempHash = gcnew Hashtable(iterators_);

IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();

What the heck does the caret mean? (The gcnew is also new to me, and I asked about that here.)

8 Answers

This is C++/CLI and the caret is the managed equivalent of a * (pointer) which in C++/CLI terminology is called a 'handle' to a 'reference type' (since you can still have unmanaged pointers).

(Thanks to Aardvark for pointing out the better terminology.)

It means that this is a reference to a managed object vs. a regular C++ pointer. Objects behind such references are managed by the runtime and can be relocated in the memory. They are also garbage-collected automatically.

When you allocated managed memory, that memory can be moved around by the garbage collector. The ^ operator is a pointer for managed memory which continues to point to the correct place even if the garbage collector moves the object it points to.

It means that it is a reference to a managed object.

It's also worth considering the following couple of sentences, that put the answer in a slightly different way:

"The handle declarator (^, pronounced "hat"), 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."

"Because native C++ pointers (*) and references (&) are not managed references, the garbage collector cannot automatically update the addresses they point to. To solve this problem, use the handle declarator to specify a variable that the garbage collector is aware of and can update automatically."

(And "native" is I.M.H.O. a better word than 'handle', as handle is possibly a word that was brought more so in by the use of the 'Windows SDK')

Related