Stupid Question 126: What is a hat type or handle declarator in C++/CX?
What is a hat type?
I’m getting more and more comfy with my latest crush WinRT, and as I do I’ve decided to learn more about the language projections even though I wont necessarily learn to be fluent in all of them (I am of course talking about C++ here). The step by step guide I did in C# and XAML for Windows Store Apps will be redone in JavaScript and Html, and I’ve been having a big of a read in RE to C++ and Windows Store Apps so I’ll be able to answer or know where to look for answers, if I get any C++ and WinRT questions during the sessions I’ll be giving the next few months on Windows Store Apps.
So a first question, which fits very nicely with the previous (but still ongoing, pointer series some questions: What is a pointer?) is what is a hat type in C++/CX?
Example: ArrayList ^ arr = gcnew ArrayList();
The ^ actually indicates a managed pointer. What it does is that it declares a handle to an object on the managed heap, it used to be _gc but the hat ^ (the handle declarator) has replaced it. It points to the whole object , and you cannot do pointer arithmetic, but on the other hand it gives you type conversion capabilities. You should use the gcnew keyword which creates a new instance of a managed type so it will automatically be garbage collected.
Comments
That's a good description of C++/CLI, the generation of managed C++ introduced with Visual Studio 2005. However in C++/CX the syntax was reused with a subtly different meaning. A C++/CX hat variable is a reference counted pointer natively understood by the compiler, but otherwise similar to ATL's CComPtr. (I first learned this in one of Herb Sutter's Build 2011 talks (see slide 12 in particular), where I was convinced he was confused until I learned what C++/CX really was.)
You are all right, yet wrong also: The hat, or handle declarator, has a very different underlying implementation depending on whether your code is native (compiled with /ZW) or managed (compiled with /CLI). The native version is basically a COM smart pointer, and the CLI version is a handle to a garbage collected object. Also, one should use "ref new" instead of gcnew, which is what ref new does under CLI anyway. To confuse matters more, some compiler errors say "/CLI is required" when /ZW will work also.
Last modified on 2013-01-13