{"id":2223,"date":"2012-09-17T10:00:00","date_gmt":"2012-09-17T10:00:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/vcblog\/2012\/09\/17\/ccx-part-2-of-n-types-that-wear-hats\/"},"modified":"2019-02-18T18:41:34","modified_gmt":"2019-02-18T18:41:34","slug":"ccx-part-2-of-n-types-that-wear-hats","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/cppblog\/ccx-part-2-of-n-types-that-wear-hats\/","title":{"rendered":"C++\/CX Part 2 of [n]: Types That Wear Hats"},"content":{"rendered":"<p><em>See <a href=\"https:\/\/blogs.msdn.microsoft.com\/vcblog\/2012\/08\/29\/ccx-part-0-of-n-an-introduction\/\">C++\/CX Part 0 of [N]: An Introduction<\/a> for an introduction to this series.<\/em><\/p>\n<p>The hat (<code>^<\/code>) is one of the most prominent features of C++\/CX&#8211;it&#8217;s hard not to notice it when one first sees C++\/CX code. So, what exactly is a <code>^<\/code> type? A hat type is a smart pointer type that (1) automatically manages the lifetime of a Windows Runtime object and (2) provides automatic type conversion capabilities to simplify use of Windows Runtime objects.<\/p>\n<p>We&#8217;ll start off by discussing how Windows Runtime objects are used via WRL, then explain how the C++\/CX hat works to make things simpler. For demonstration purposes, we&#8217;ll use the following modified version of the <code>Number<\/code> class that we introduced in Part 1:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">public<\/span>&nbsp;<span style=\"color: blue\">interface<\/span>&nbsp;<span style=\"color: blue\">struct<\/span>&nbsp;<span style=\"color: #2b91af\">IGetValue<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;GetValue()&nbsp;=&nbsp;0;\n&nbsp;&nbsp;&nbsp;&nbsp;};\n<\/pre>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">public<\/span>&nbsp;<span style=\"color: blue\">interface<\/span>&nbsp;<span style=\"color: blue\">struct<\/span>&nbsp;<span style=\"color: #2b91af\">ISetValue<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">void<\/span>&nbsp;SetValue(<span style=\"color: blue\">int<\/span>&nbsp;value)&nbsp;=&nbsp;0;\n&nbsp;&nbsp;&nbsp;&nbsp;};\n<\/pre>\n<pre style=\"background: white;color: black;font-family: Consolas\">\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">public<\/span>&nbsp;<span style=\"color: blue\">ref<\/span>&nbsp;<span style=\"color: blue\">class<\/span>&nbsp;<span style=\"color: #2b91af\">Number<\/span>&nbsp;<span style=\"color: blue\">sealed<\/span>&nbsp;:&nbsp;<span style=\"color: blue\">public<\/span>&nbsp;<span style=\"color: #2b91af\">IGetValue<\/span>,&nbsp;<span style=\"color: #2b91af\">ISetValue<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">public<\/span>:\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Number()&nbsp;:&nbsp;_value(0)&nbsp;{&nbsp;}\n<\/pre>\n<pre style=\"background: white;color: black;font-family: Consolas\">\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">virtual<\/span>&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;&nbsp;GetValue()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;<span style=\"color: blue\">return<\/span>&nbsp;_value;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">virtual<\/span>&nbsp;<span style=\"color: blue\">void<\/span>&nbsp;SetValue(<span style=\"color: blue\">int<\/span>&nbsp;<span style=\"color: gray\">value<\/span>)&nbsp;{&nbsp;_value&nbsp;=&nbsp;<span style=\"color: gray\">value<\/span>;&nbsp;}\n<\/pre>\n<pre style=\"background: white;color: black;font-family: Consolas\">\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">private<\/span>:\n<\/pre>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;_value;\n&nbsp;&nbsp;&nbsp;&nbsp;};<\/pre>\n<p>In this modified <code>Number<\/code> implementation, we define a pair of interfaces, <code>IGetValue<\/code> and <code>ISetValue<\/code>, that declare the two member functions of <code>Number<\/code>; <code>Number<\/code> then implements these two interfaces. Otherwise, things should look pretty familiar.<\/p>\n<p>Note that <code>Number<\/code> actually implements three Windows Runtime interfaces: in addition to <code>IGetValue<\/code> and <code>ISetValue<\/code>, the compiler still generates the <code>__INumberPublicNonVirtuals<\/code> interface, which <code>Number<\/code> implements. Because all of the members of <code>Number<\/code> are declared by explicitly implemented interfaces (<code>IGetValue<\/code> and <code>ISetValue<\/code>), the compiler-generated <code>__INumberPublicNonVirtuals<\/code> does not declare any members. This interface is still required, though, as it is the <em>default interface<\/em> for the <code>Number<\/code> type. Every runtime type must have one default interface, and the default interface should almost always be unique to the class. We&#8217;ll see why the default interface is important a bit later.<\/p>\n<h2>Lifetime Management<\/h2>\n<p>Windows Runtime reference types use reference counting for object lifetime management. All Windows Runtime interfaces (including all three of the interfaces implemented by <code>Number<\/code>) derive directly from the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/br205821.aspx\"><code>IInspectable<\/code><\/a> interface, which itself derives from the COM <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms680509.aspx\"><code>IUnknown<\/code><\/a> interface. <code>IUnknown<\/code> declares three member functions that are used to control the lifetime of an object and to allow type conversion.<\/p>\n<p>The MSDN article <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms692481.aspx\">&#8220;Rules for Managing Reference Counts&#8221;<\/a> has a thorough overview of how <code>IUnknown<\/code> lifetime management works. The principles are quite straightforward, though: whenever you create a new reference to an object, you must call <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms691379.aspx\"><code>IUnknown::AddRef<\/code><\/a> to increment its reference count; whenever you &#8220;destroy&#8221; a reference to an object, you must call <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms682317.aspx\"><code>IUnknown::Release<\/code><\/a> to decrement the reference count. The reference count is initialized to zero, and after a series of calls to <code>AddRef<\/code> and <code>Release<\/code>, when the reference count reaches zero again, the object destroys itself.<\/p>\n<p>Of course, when programming in C++, we should rarely&#8211;practically never&#8211;call <code>AddRef<\/code> and <code>Release<\/code> directly. Instead, we should prefer wherever possible to use a smart pointer that automatically makes these calls when they are required. Use of a smart pointer helps to ensure that objects are neither leaked due to a missed <code>Release<\/code> nor prematurely destroyed due to a premature <code>Release<\/code> or failure to <code>AddRef<\/code>.<\/p>\n<p>ATL includes <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ezzw7k98.aspx\"><code>CComPtr<\/code><\/a> and a family of related smart pointers that have long been used in COM programming for automatically managing the reference counting of objects that implement <code>IUnknown<\/code>. WRL includes <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/br244983.aspx\"><code>ComPtr<\/code><\/a>, which is an improved and modernized <code>CComPtr<\/code> (an example improvement: <code>ComPtr<\/code> does not overload the unary <code>&amp;<\/code> like <code>CComPtr<\/code> does).<\/p>\n<p>For those who have not done much COM programming and are unfamiliar with <code>ComPtr<\/code>s: if you&#8217;ve used <code>shared_ptr<\/code> (included as part of C++11, C++ TR1, and Boost), <code>ComPtr<\/code> has effectively the same behavior with respect to lifetime management. The mechanism is different (<code>ComPtr<\/code> makes use of the internal reference counting provided by <code>IUnknown<\/code>, while <code>shared_ptr<\/code> supports arbitrary types and must thus use an external reference count), but the lifetime management behavior is the same.<\/p>\n<p>The C++\/CX hat has exactly the same lifetime management semantics as a <code>ComPtr<\/code>. When a <code>T^<\/code> is copied, <code>AddRef<\/code> is called to increment the reference count, and when a <code>T^<\/code> goes out of scope or is reassigned, <code>Release<\/code> is called to decrement the reference count. We can consider a simple example to demonstrate the reference counting behavior:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">T<\/span>^&nbsp;t0&nbsp;=&nbsp;<span style=\"color: blue\">ref<\/span>&nbsp;<span style=\"color: blue\">new<\/span>&nbsp;<span style=\"color: #2b91af\">A<\/span>();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">T<\/span>^&nbsp;t1&nbsp;=&nbsp;<span style=\"color: blue\">ref<\/span>&nbsp;<span style=\"color: blue\">new<\/span>&nbsp;<span style=\"color: #2b91af\">B<\/span>();\n<\/pre>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t0&nbsp;=&nbsp;t1;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t0&nbsp;=&nbsp;<span style=\"color: blue\">nullptr<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/pre>\n<p>First, we create an <code>A<\/code> object and give ownership of it to <code>t0<\/code>. The reference count of this <code>A<\/code> object is 1 because there is one <code>T^<\/code> that has a reference to it. We then create a <code>B<\/code> object and give ownership of it to <code>t1<\/code>. The reference count of this <code>B<\/code> object is also 1.<\/p>\n<p>The end result of <code>t0 = t1<\/code> is that both <code>t0<\/code> and <code>t1<\/code> point to the same object. This must be done in three steps. First, <code>t1-&gt;AddRef()<\/code> is called to increment the reference count of the <code>B<\/code> object, because <code>t1<\/code> is gaining ownership of the object. Second, <code>t0-&gt;Release()<\/code> is called to release <code>t0<\/code>&#8216;s ownership of the <code>A<\/code> object. This causes the reference count of the <code>A<\/code> object to drop to zero and the <code>A<\/code> object destroys itself. This causes the reference count of the <code>B<\/code> object to increase to 2. Third and finally, <code>t1<\/code> is set to point to the <code>B<\/code> object.<\/p>\n<p>We then assign <code>t0 = nullptr<\/code>. This &#8220;resets&#8221; <code>t0<\/code> to be null, which causes it to release its ownership of the <code>B<\/code> object. This calls <code>t0-&gt;Release()<\/code>, causing the reference count of the <code>B<\/code> object to decrease to 1.<\/p>\n<p>Finally, execution will reach the closing brace of the block: <code>}<\/code>. At this point, all of the local variables are destroyed, in reverse order. First, <code>t1<\/code> is destroyed (the smart pointer, not the object pointed to). This calls <code>t1-&gt;Release()<\/code>, causing the reference count of the <code>B<\/code> object to drop to zero, so the <code>B<\/code> object destroys itself. <code>t0<\/code> is then destroyed, which is a no-op because it is null.<\/p>\n<p>If lifetime management was our only concern, there wouldn&#8217;t really be a need for the <code>^<\/code> at all: <code>ComPtr&lt;T&gt;<\/code> is sufficient to manage object lifetime.<\/p>\n<h2>Type Conversion<\/h2>\n<p>In C++, some type conversions involving class types are implicit; others may be performed using a cast or a series of casts. For example, if <code>Number<\/code> and the interfaces it implements were ordinary C++ types and not Windows Runtime types, conversion from <code>Number*<\/code> to <code>IGetValue*<\/code> would be implicit, and we could convert from <code>IGetValue*<\/code> to <code>Number*<\/code> using a <code>static_cast<\/code> or a <code>dynamic_cast<\/code>.<\/p>\n<p>These conversions do not work with Windows Runtime reference types because the implementation of a reference type is opaque and the layout of a reference type in memory is left unspecified. A reference type implemented in C# may be laid out in memory differently from an equivalent reference type implemented in C++. Thus, we cannot rely on C++ language specific features like implicit derived-to-base conversions and casts when working directly with Windows Runtime types.<\/p>\n<p>To perform these conversions, we must instead use the third member function of the <code>IUnknown<\/code> interface: <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms682521.aspx\"><code>IUnknown::QueryInterface<\/code><\/a>. This member function can be considered as a language-neutral <code>dynamic_cast<\/code>: it attempts to perform a conversion to the specified interface and returns whether the conversion succeeded. Because each runtime type implements the <code>IUnknown<\/code> interface and provides its own definition for <code>QueryInterface<\/code>, it can do whatever is required to get the correct interface pointer in the language and framework with which it is implemented.<\/p>\n<h2>Using an object via WRL<\/h2>\n<p>Let&#8217;s take a look at how we&#8217;d use our <code>Number<\/code> class via WRL. This example accepts an instance of <code>Number<\/code> and calls <code>SetValue<\/code> to set the value and <code>GetValue<\/code> to get the value back. (Error checking has been omitted for brevity.)<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">void<\/span>&nbsp;F(<span style=\"color: #2b91af\">ComPtr<\/span>&lt;<span style=\"color: #2b91af\">__INumberPublicNonVirtuals<\/span>&gt;&nbsp;<span style=\"color: blue\">const<\/span>&amp;&nbsp;<span style=\"color: gray\">numberIf<\/span>)\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: green\">\/\/&nbsp;Get&nbsp;a&nbsp;pointer&nbsp;to&nbsp;the&nbsp;object's&nbsp;ISetValue&nbsp;interface&nbsp;and&nbsp;set&nbsp;the&nbsp;value:<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">ComPtr<\/span>&lt;<span style=\"color: #2b91af\">ISetValue<\/span>&gt;&nbsp;setValueIf;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: gray\">numberIf<\/span>.As(&amp;setValueIf);\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setValueIf-&gt;SetValue(42);\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: green\">\/\/&nbsp;Get&nbsp;a&nbsp;pointer&nbsp;to&nbsp;the&nbsp;object's&nbsp;IGetValue&nbsp;interface&nbsp;and&nbsp;get&nbsp;the&nbsp;value:<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">ComPtr<\/span>&lt;<span style=\"color: #2b91af\">IGetValue<\/span>&gt;&nbsp;getValueIf;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: gray\">numberIf<\/span>.As(&amp;getValueIf);\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;value&nbsp;=&nbsp;0;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;getValueIf-&gt;GetValue(&amp;value);\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/pre>\n<p>The <code>As<\/code> member function template of the WRL <code>ComPtr<\/code> simply encapsulates a call to <code>IUnknown::QueryInterface<\/code> in a way that helps to prevent common programming errors. We use this first to get the <code>ISetValue<\/code> interface pointer to call <code>SetValue<\/code> then again to get the <code>IGetValue<\/code> interface pointer to call <code>GetValue<\/code>.<\/p>\n<p>This would be a lot simpler if we obtained a <code>Number*<\/code> and called <code>SetValue<\/code> and <code>GetValue<\/code> via that pointer. Unfortunately, we can&#8217;t do that: recall that the implementation of a reference type is opaque and that we only ever interact with an object via a pointer to one of the interfaces that it implements. This means that we can never have a <code>Number*<\/code>; there is really no such thing. Rather, we can only refer to a <code>Number<\/code> object via an <code>IGetValue*<\/code>, an <code>ISetValue*<\/code>, or an <code>__INumberPublicNonVirtuals*<\/code>.<\/p>\n<p>This is an awful lot of code just to call two member functions and this example demonstrates one of the key hurdles that we have to overcome to make it easier to use Windows Runtime types. Unlike COM, Windows Runtime does not allow an interface to derive from another Windows Runtime interface; all interfaces must derive directly from <code>IInspectable<\/code>. Each interface is independent, and we can only interact with an object via interfaces, so if we are using a type that implements multiple interfaces (which many types do), we are stuck having to write a lot of rather verbose type conversion code so that we can obtain the correct interface pointer to make each function call.<\/p>\n<h2>Using an object via C++\/CX<\/h2>\n<p>One of the key advantages of C++\/CX is that the compiler knows which types are Windows Runtime types. It has access to the Windows Metadata (WinMD) file that defines each interface and runtime type, so&#8211;among other things&#8211;it knows the set of interfaces that each runtime type implements. For instance, the compiler knows that the <code>Number<\/code> type implements the <code>ISetValue<\/code> and <code>IGetValue<\/code> interfaces, because the metadata specifies that it does. The compiler is able to use this type information to automatically generate type conversion code.<\/p>\n<p>Consider the following C++\/CX example, which is equivalent to the WRL example that we presented:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">void<\/span>&nbsp;F(<span style=\"color: #2b91af\">Number<\/span>^&nbsp;<span style=\"color: gray\">number<\/span>)\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">ISetValue<\/span>^&nbsp;setValueIf&nbsp;=&nbsp;<span style=\"color: gray\">number<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setValueIf-&gt;SetValue(42);\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">IGetValue<\/span>^&nbsp;getValueIf&nbsp;=&nbsp;<span style=\"color: gray\">number<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;value&nbsp;=&nbsp;getValueIf-&gt;GetValue();\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/pre>\n<p>Because the compiler knows that the <code>Number<\/code> type implements the <code>ISetValue<\/code> and <code>IGetValue<\/code> interfaces, it allows implicit conversion from <code>Number^<\/code> to <code>ISetValue^<\/code> and <code>IGetValue^<\/code>. This implicit conversion causes the compiler to generate a call to <code>IUnknown::QueryInterface<\/code> to get the right interface pointer. Aside from the cleaner syntax, there&#8217;s really no magic here: the compiler is just generating the type conversion code that we otherwise would have to write ourselves.<\/p>\n<p><code>dynamic_cast<\/code> also works much as we&#8217;d expect: we can, for example, amend this example to obtain the <code>IGetValue^<\/code> from the <code>ISetValue^<\/code>:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">void<\/span>&nbsp;F(<span style=\"color: #2b91af\">Number<\/span>^&nbsp;<span style=\"color: gray\">number<\/span>)\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">ISetValue<\/span>^&nbsp;setValueIf&nbsp;=&nbsp;<span style=\"color: gray\">number<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setValueIf-&gt;SetValue(42);\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">IGetValue<\/span>^&nbsp;getValueIf&nbsp;=&nbsp;<span style=\"color: blue\">dynamic_cast<\/span>&lt;<span style=\"color: #2b91af\">IGetValue<\/span>^&gt;(setValueIf);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;value&nbsp;=&nbsp;getValueIf-&gt;GetValue();\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/pre>\n<p>This example has the same behavior as the first example, we just take different steps to get that same behavior. <code>dynamic_cast<\/code> can return <code>nullptr<\/code> if the cast fails (though we know that it will succeed in this specific case). C++\/CX also provides <code>safe_cast<\/code>, which throws a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/hh755790.aspx\"><code>Platform::InvalidCastException<\/code><\/a> exception if the cast fails.<\/p>\n<p>When we discussed the WRL example above, we noted that there&#8217;s no such thing as a <code>Number*<\/code>: we only ever work with interface pointers. This begs the question: what is a <code>Number^<\/code>? At runtime, a <code>Number^<\/code> is a <code>__INumberPublicNonVirtuals^<\/code>. A hat that refers to a runtime type (and not an interface) actually holds a pointer to the default interface of that runtime type.<\/p>\n<p>At compile-time, though, the compiler treats <code>Number^<\/code> as if it refers to the whole <code>Number<\/code> object. The compiler aggregates all of the members of all of the interfaces implemented by <code>Number<\/code> and allows all of those members to be called directly via a <code>Number^<\/code>. We can use a <code>Number^<\/code> as if it were an <code>IGetValue^<\/code> or an <code>ISetValue^<\/code> and the compiler will inject the required calls to <code>QueryInterface<\/code> to perform the conversions required to make the function call.<\/p>\n<p>Therefore, we can shorten our C++\/CX program further:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">void<\/span>&nbsp;F(<span style=\"color: #2b91af\">Number<\/span>^&nbsp;<span style=\"color: gray\">number<\/span>)\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: gray\">number<\/span>-&gt;SetValue(42);\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;value&nbsp;=&nbsp;<span style=\"color: gray\">number<\/span>-&gt;GetValue();\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/pre>\n<p>This code does exactly the same thing as our first C++\/CX example and as our WRL example. There&#8217;s still no magic: the compiler is simply generating all of the boilerplate to perform the type conversion required to make each function call.<\/p>\n<p>You may have noticed that this example is much shorter and less verbose than the WRL example that we started with. \ud83d\ude42 All of the boilerplate is gone and we&#8217;re left with code that&#8211;aside from the <code>^<\/code> and <code>ref<\/code> that tell the compiler we are dealing with Windows Runtime types&#8211;looks exactly like similar C++ code that interacts with ordinary C++ types. This is the point, though: ideally our code that uses Windows Runtime types should be as similar as possible to code that uses C++ types.<\/p>\n<h2>Final Notes<\/h2>\n<p>Both <code>ComPtr&lt;T&gt;<\/code> and <code>T^<\/code> are &#8220;no-overhead&#8221; smart pointers: the size of each is the same as the size of an ordinary pointer, and operations using them do not do any unnecessary work. If you need to interoperate between code that uses C++\/CX and code that uses WRL, you can simply use <code>reinterpret_cast<\/code> to convert a <code>T^<\/code> to a <code>T*<\/code>:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">    ABI::<span style=\"color: #2b91af\">ISetValue<\/span>*&nbsp;setValuePtr&nbsp;=&nbsp;<span style=\"color: blue\">reinterpret_cast<\/span>(setValueIf);\n<\/pre>\n<p>(The ABI level definitions of types are defined in namespaces under the <code>ABI<\/code> namespace so that they do not conflict with the &#8220;high-level&#8221; definitions of the types used by C++\/CX, which are defined under the global namespace.)<\/p>\n<p>In addition to its type conversion capabilities, the hat provides other benefits that could not otherwise be accomplished via use of an ordinary smart pointer like <code>ComPtr<\/code>. One of the most important of these benefits is that the hat can be used uniformly, everywhere. A member function that takes an interface pointer as an argument is declared as taking a raw pointer (this is part of the Windows Runtime ABI, which is designed to be simple and language-neutral, and thus knows nothing of what a C++ smart pointer is). So, while one can use <code>ComPtr<\/code> most places, raw pointers still need to be used at the ABI boundary, and there is room for subtle (and not-so-subtle) programming errors.<\/p>\n<p>With C++\/CX, the compiler already transforms member function signatures to translate between exceptions and HRESULTs and the compiler is also able to inject conversions from <code>T^<\/code> to <code>T*<\/code> where required, substantially reducing the opportunity for programming errors.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>See C++\/CX Part 0 of [N]: An Introduction for an introduction to this series. The hat (^) is one of the most prominent features of C++\/CX&#8211;it&#8217;s hard not to notice it when one first sees C++\/CX code. So, what exactly is a ^ type? A hat type is a smart pointer type that (1) automatically [&hellip;]<\/p>\n","protected":false},"author":289,"featured_media":35994,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[121,132,160],"class_list":["post-2223","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cplusplus","tag-ccx","tag-windows-8","tag-windows-store-apps"],"acf":[],"blog_post_summary":"<p>See C++\/CX Part 0 of [N]: An Introduction for an introduction to this series. The hat (^) is one of the most prominent features of C++\/CX&#8211;it&#8217;s hard not to notice it when one first sees C++\/CX code. So, what exactly is a ^ type? A hat type is a smart pointer type that (1) automatically [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts\/2223","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/users\/289"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/comments?post=2223"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts\/2223\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/media\/35994"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/media?parent=2223"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/categories?post=2223"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/tags?post=2223"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}