title: C++/CX: Why doesn't returning a StringReference work like passing one as an argument?
body: <p><code>Platform::StringReference</code> exists so that you can pass a <code>const wchar_t*</code> across the ABI boundary to a function accepting a <code>String^</code> without making a copy.  The <code>StringReference</code> implicitly converts to a <code>String^</code> whose internal pointer matches the original <code>const wchar_t*</code>.  This is verified by the following code; if you step through it you find that <code>pz == z</code>:</p>
  
  <pre><code>void param(String^ s)
  {
      const wchar_t* z = s-&gt;Data();
  }
  
  App::App()
  {
      std::wstring p = L"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
      const wchar_t* pz = p.c_str();
      param(StringReference(pz));
  }
  </code></pre>
  
  <p>However, trying to return a <code>StringReference</code> doesn't seem to work the same way and I'm curious why.  If I have a function that returns <code>String^</code> and I return a <code>StringReference</code> from it then the same implicit conversion operator is called, but when the caller gets their <code>String^</code> it has a different internal data pointer that contains a copy.  Here's some code that tries it:</p>
  
  <pre><code>String^ ret()
  {
      std::wstring s = L"12345678901234567890123456789012345678901234567890";
      const wchar_t* z = s.c_str();
      return StringReference(z);
  }
  
  App::App()
  {
      String^ r = ret();
      const wchar_t* rz = r-&gt;Data();
  }
  </code></pre>
  
  <p>That code verifies in two ways: first, if you step through you'll find that <code>z != rz</code> and second, <code>r</code> ends up pointing to a valid string rather than garbage, so a copy must have been made because the original string is freed at the end of <code>ret</code>.</p>
  
  <p>I also tried returning via out parameter, but I get the same results as a straight return (<code>z != oz</code> and <code>o</code> ends up with a valid string):</p>
  
  <pre><code>void out(String^* r)
  {
      std::wstring s = L"12345678901234567890123456789012345678901234567890";
      const wchar_t* z = s.c_str();
      *r = StringReference(z);
  }
  
  App::App()
  {
      String^ o;
      out(&amp;o);
      const wchar_t* oz = o-&gt;Data();
  }
  </code></pre>
  
  <p>Is there a way to return a <code>StringReference</code> across the ABI boundary in the same way that you can pass one?  I imagine the behavior would depend on the language of the caller and how that language marshals strings from WinRT, but it seems like at least a C++/CX caller ought to be able to do it.</p>