LoginSignup
14
14

More than 5 years have passed since last update.

staticメンバ変数は使わないこと!

Last updated at Posted at 2016-03-04

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からスレッドセーフが保証されたはず)

出展: c++ more idioms Construct On First Use

14
14
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14