This page last changed on Oct 19, 2006 by mmccorma.

Never do this:

void f() {
  static int x = 10;
}

Static on a local variable means the compiler is supposed initialize it the first time the function is entered, but it holds its value on subsequent calls. It's sometimes used for local counters, or in the "Myers Singleton" approach to singletons.

The problem is that the C++ standard does not require compilers to make this initialization thread safe, and almost none do. So in a multi threaded program if there are concurrent first calls to f there will be a disaster. Using this for singletons is particularly prone to multi-threaded collisions.

So use the less elegant but safer options: make the variable a class member for member functions or a file-private global for non-member functions.

Document generated by Confluence on Apr 22, 2008 02:47