qpid-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Apache Wiki <wikidi...@apache.org>
Subject [Qpid Wiki] Update of "CppTips/NeverUseStaticLocalVariables" by AlanConway
Date Tue, 19 Sep 2006 12:31:08 GMT
Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Qpid Wiki" for change notification.

The following page has been changed by AlanConway:
http://wiki.apache.org/qpid/CppTips/NeverUseStaticLocalVariables

New page:
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.

Mime
View raw message