Meyers Item 4 Singleton in presence of threading

Jonathan Wakely jwakely.gcc@gmail.com
Tue Nov 23 05:52:00 GMT 2010


> I'd agree with that, if you drop the static and initialize explicitly:
>
> T localT = (T)0;
>
> but then, each thread has its own localT, zeroed each time it comes into scope.

And for many T (e.g. std::string) you'll crash at runtime. Nice.
And you can't return a reference to a local. And you don't have a singleton.
So this answer seems quite unrelated to the original question!

Miles is right, g++ initializes function-scope statics in a threadsafe
manner, as will be required by C++0x.
See libstdc++-v3/libsupc++/guard.cc for the implementation.

If you need to initialize the T (e.g. because it's a POD) don't do it
by casting from zero. Instead do:

T& getaccess()
{
    static T localT = T();
    return localT;
}



More information about the Gcc-help mailing list