This article is more than 1 year old

Binary interfaces in component development

A template class with static data - how can that possibly go wrong?

What’s the solution? Unfortunately, the solution is to choose a software architecture that doesn’t expose you to this incoherence between dynamic libraries and static data. In the example we’ve seen, the problem comes from how dynamic libraries work on windows, but on Linux, there are equivalent ways to get stung by this issue. [If people are interested leave a comment and we can look at it next time.]

In conclusion, what do we think the specific problems are with this architecture, which then led us into this trap? Firstly, the person who came up with the idea of using a class template to implement the singleton pattern needs to be spoken to severely. Management of static data is always so problematic in C++ that when it is used, the location of its definition must be carefully considered, so that the same definition is used in all places that it is needed. To choose an implementation technique such as templates, that obliges the compiler to put definitions of the same piece of static data in every object file for a pattern that exists to manage static data, is a little thoughtless.

Secondly, there are times when we do really need static data in templates. Not for a Singleton pattern, we’re probably all agreed; but sometimes it can be an extremely powerful implementation tool. In these cases, we should manage the location of the definition carefully, by not exposing the template definitions in the interfaces and instead using explicit instantiation at the appropriate place. The cost of explicit instantiation is that the template can only be used for types that are known to the template definition in advance; but if you don’t do this, you guarantee later problems for yourself, when running with dynamic libraries on Windows.

Finally, you can use the same code with explicit instantiation – it now works but this shouldn’t be regarded as a fix for the implementation, as the cost of having to know all Singleton types in advance is a big problem for this class. And a further note: for all the trouble caused by the template implementation, could we not just have written a non-template version, and duplicated the two lines of code whenever we needed to?

Resources:

The Win32 Portable Executable File Format: http://msdn.microsoft.com/msdnmag/issues/02/02/PE/.

The PEBrowse Windows disassembler and static-analysis tool: http://www.smidgeonsoft.prohosting.com/pebrowse-pro-file-viewer.html.

The program linker and what it does: http://www.microsoft.com/msj/0797/hood0797.aspx.

The Sourcecode used for this article, in a zip archive.

More about

TIP US OFF

Send us news


Other stories you might like