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…





    // Do something with interface pointers





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;





    // 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.)


A simple 2D matrix class

There is a recurring question on some C++ forums about nesting std::vector’s to build a 2D matrix, i.e.:

    std::vector< std::vector<double> > someMatrix;


This is not very efficient, both memory-wise and speed-wise.

In fact, each vector has an overhead due to the fact that it typically stores three pointers. So, e.g. in case of a 20 rows by 30 columns matrix, assuming that inner vectors represent matrix rows, the overhead is 20 rows x 3 pointers/row = 60 pointers, i.e. 60 pointers x 4 bytes/pointer = 240 bytes.

But there is also a speed penalty. In fact, dynamic memory allocated by each vector is in general scattered on the heap; instead, it would be better for locality to have contiguous memory allocated for the whole matrix.

So, a better technique consists in using just one instance of std::vector, storing all matrix elements in this very instance, using a proper ordering for elements, e.g. storing matrix elements row-wise.

The total size of the vector is rows * columns, and given a 2D index (row, column) it can be “linearized” to point to proper vector element using the following formula:

<vector index> = <column index> + <row index> * <matrix columns>

These concepts are developed in a simple reusable C++ template class attached to this blog post. This is a simple class for simple needs (i.e. just storing 2D matrix elements in an efficient way and accessing them conveniently). For more advanced matrix classes, with template meta-programming optimizations, Blitz++ library can be considered.


STL Introductory Series on Channel 9

Stephan concluded his introductory series on the STL with an interesting chapter on template metaprogramming and type traits.

In addition to previous lessons, here is a complete list of this ten part series introducing the STL:

Part 1 is about sequence containers (like std::vector).

Part 2 is on associative containers (like std::map).

Part 3 discusses smart pointers (e.g. shared_ptr).

Parts 4 and 5 show a practical use of the aforementioned concepts applied to the development of a Nurikabe puzzle solver.

Part 6 and part 7 discuss STL algorithms.

Part 8 is about regular expressions.

In part 9 new C++0x core language features like r-value references and move semantics are discussed.

And finally part 10 is about template metaprogramming and type traits.

Thank you Stephan and Channel 9 for this quality introduction to the STL!


Checked Iterators

Microsoft Visual Studio versions since VC8 (VS2005) offer a feature called “checked iterators”. The MSDN documentation clearly states: “Checked iterators ensure that you do not overwrite the bounds of your container. Checked iterators apply to release builds and debug builds.Checked iterators can be disabled #defining the _SECURE_SCL symbol to 0.

In VC8 (VS2005) and VC9 (VS2008), checked iterators are enabled by default in both debug and release builds. While I agree that having checked iterators enabled by default in debug builds is a good thing (because debug builds are designed to catch as much bugs as possible), I think the default behavior in release builds should be to switch checked iterators off. In fact, I do like speed in release builds.

As a simple benchmark (attached to this blog post), on an Intel Core 2 Duo @ 2.33 GHz, switching checked iterators off improved a simple 1,000×1,000 matrix multiplication time from 20 seconds to about 12 seconds (a 40% improvement).

I like putting the following lines in precompiled header file, to switch checked iterators off in release builds:

// Disable checked iterators in release builds

#ifndef _DEBUG

#define _SECURE_SCL 0



Fortunately, in VS2010, in release mode, the default value for _SECURE_SCL is 0.

Web Resources on Windows Programming in C++

I’d like to point out some interesting links to resources on Windows programming in C++.

Learn to Program for Windows in C++” is a series published on MSDN, aimed at teaching how to write a Windows program in C++, assuming a good working knowledge of C++ programming, but no previous experience in Windows programming. Things like Windows typical terminology, window classes, window procedure, window messages, using COM,  Windows graphics architecture, handling user input, etc. are explained.

Specific resources about Windows 7 Taskbar programming can be found here.

Another interesting series on Windows C++ programming is Hilo. Several topics are discussed, ranging from Direct2D, to animation manager, to Windows Ribbon, Windows Imaging component, Windows 7 Web Services API, etc.

And, last but not least, Kenny Kerr (author of Window Clippings) is offering a series about C++ programming for Windows on his blog.

Relax. Enjoy. Learn.