LoginSignup
1
0

More than 5 years have passed since last update.

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

Posted at

以下のようなコードがあったとして

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;

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

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

以下の2つのコードの挙動は異なるという話

main1.cpp
#include <stdio.h>
#include "hoge.hpp"

Hoge hoge;

int main(void)
{
    hoge.showVal();
}
construct Hoge
called setVal:x = 123
construct Fuga:x = 0
val = 0
main2.cpp
#include <stdio.h>
#include "hoge.hpp"

int main(void)
{
    Hoge hoge;
    hoge.showVal();
}
construct Fuga:x = 0
construct Hoge
called setVal:x = 123
val = 123

結論:静的オブジェクトのコンストラクタで余計なことをするな

1
0
0

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
1
0