HSTRING wrapper for C++

If you are developing apps for Windows Store or Windows Phone in C++, chances are that one of the biggest annoyance you will see are the HSTRING(specifically creating and managing them.) If you are using C++/CX you can get away by using "Platform::String", but if you cannot use CX extension your only option is to use HSTRING.


C++ developers normally keep their strings in "wchar_t*" format, however Windows Runtime APIs require them in HSTRING format. APIs exists to convert between them, but you have to make sure that you call them properly, otherwise memory leaks will happen.


This class will management of HSTRINGs easier. You simply create a HStringOwner object on the stack. Once this object goes out of scope, it will be destroyed.


  1. Easy creation of HSTRING
  2. Lifetime management of HSTRING
  3. Proper cleanup of HSTRING in case of exception
  4. Allows you to return early from your function without running a block of code specifically for cleanup.


 #pragma once
 * Author : Asim Goheer
 * HStringOwner is a very lightweight helper class to make HSTRING
 * management easier. 
 * This helper will guarantee proper cleanup, becase in case of an exception
 * it's destructor will run thus releasing the string
 * This helper will also allow you to return early from a function. Because
 * when you return early from a function the destructor will automatically
 * release the string
 class HStringOwner
 HStringOwner( wchar_t* wzSource )
 HRESULT hr = WindowsCreateString( wzSource, wcslen( wzSource ), &m_hString );
 if( FAILED( hr ) )
 // throw exception here
 virtual ~HStringOwner()
 WindowsDeleteString( m_hString );
 operator HSTRING () const
 return m_hString;
 HStringOwner( const HStringOwner& );
 HSTRING m_hString;