以下のようなコードがあったとして
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
結論:静的オブジェクトのコンストラクタで余計なことをするな