COM Automatic Initialization and Cleanup (and Text to Speech…)

Suppose we have some COM code where instances of CComPtr are used to conveniently wrap COM interface pointers:


{

    HRESULT hr = CoInitialize(NULL);

    // check return value…

 

    CComPtr<ISomeInterfacesp1;

    CComPtr<IAnotherInterfacesp2;

    …

    // Do something with interface pointers

    …

    CoUninitialize();

}


 


This code hides a subtle bug: the problem is that CoUninitialize is called before the CComPtr destructors. Instead, correct logic requires that CoUninitialize must be called after every COM interface pointer is released (in its own wrapping CComPtr destructor).


Actually, there is also a problem of exception safety here. In fact, if some exception is thrown in the middle of the code block, the call to CoUninitialize is missed.


To correct both these problems, it is possible to define a C++ class following the RAII pattern. The constructor of this class will call CoInitialize, and throw an exception if initialization failed. The class destructor will call CoUninitialize; so every successful call to CoInitialize will have a matching call to CoUninitialize, as prescribed by COM programming rules.


Moreover, assuming that instances of this class are created (on the stack) before instances of CComPtr (or other COM smart pointers), CoUninitialize will be the last call, after every CComPtr destructor is called:


{

    // COM automatic initialization and cleanup

    CComAutoInit comInit;

 

    CComPtr<ISomeInterfacesp1;

    CComPtr<IAnotherInterfacesp2;

    …

    // Do something with interface pointers

    …

}

 


The complete listing of this custom CComAutoInit class is attached to this blog post. There are some additional details, like having defined private copy constructor and operator=, to ban deep-copy semantic for this class.


Moreover, there is an (explicit) overload of CComAutoInit constructor which takes a DWORD parameter corresponding to the dwCoInit parameter of CoInitializeEx.


A working sample showing how to use this CComAutoInit class is attached to this blog post as well. It is basically a C++ command line app that “speaks” the arguments passed to it. (A slightly more complex GUI dialog-based MFC text-speaker app can be found on MSDN Code Gallery, too.)


 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>