Differences between revisions 2 and 3
Revision 2 as of 2006-10-19 10:02:37
Size: 862
Editor: dbws1bcx04
Revision 3 as of 2009-09-20 23:51:28
Size: 862
Editor: localhost
Comment: converted to 1.6 markup
No differences found!

MIGRATED to http://cwiki.apache.org/confluence/display/qpid/NeverUseStaticLocalVariables

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.

CppTips/NeverUseStaticLocalVariables (last edited 2009-09-20 23:51:28 by localhost)