staticメンバ変数は、初期化前に使用されてしまう可能性がある。
struct foo
{
foo() { std::puts("foo"); }
void f() { std::puts("f"); }
};
struct sth
{
static foo foo_;
sth() { foo_.f(); }
};
sth s; // oops!
foo sth::foo_;
これを回避し、確実にstaticメンバ変数を使用前に初期化するには、以下のようにする。
struct sth
{
static foo& foo_()
{
static foo f;
return (f);
}
sth() { foo_().f(); }
};
staticメンバ関数で包んだだけだが、これで確実に初期化されることが保証される。
加えて、c++11からはスレッドセーフである。(visual studioでは2015からスレッドセーフが保証されたはず)