LoginSignup
0

More than 5 years have passed since last update.

静的メンバ変数を静的クラスのコンストラクタでアクセスしてはいけないのか?(追記)

Posted at

http://qiita.com/rai_suta/items/332a6746561301f7f249
からの追記

この問題の対策案を書いてらっしゃる方[1]を見つけたので、参考に自分のコードを書きなおしてみる

hoge.hpp
class Fuga {
public:
    int val;
    Fuga(int x=0);
    void
    setVal(int x);
};

class Hoge {
    static Fuga& fuga();
public:
    Hoge();
    void
    showVal();
};
hoge.cpp
#include "hoge.hpp"
#include <stdio.h>

Fuga::Fuga(int x){
    printf("construct Fuga:x = %d\n", x);
    val = x;
}

void
Fuga::setVal(int x){
    printf("called setVal:x = %d\n", x);
    val = x;
}

Fuga& Hoge::fuga(){
    static Fuga v;
    return v;
}

Hoge::Hoge(){
    printf("construct Hoge\n");
    fuga().setVal(123);
}

void
Hoge::showVal(){
    printf("val = %d\n", fuga().val);
}

[1]http://giftserver.dip.jp/anotherproject/html_l5/develop/pgmemo/static_constructor.htm

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
0