Static members

Started by
3 comments, last by SiCrane 12 years, 1 month ago
Is this safe?


// Foo.hpp
struct Foo
{
static int s1;
static int s2;
static int func()
{
return s2 * 3;
}
};



// Foo.cpp
int Foo::s1 = 6;
int Foo::s2 = s1 * 2;


...and then use it elswhere.
1. Is s1 guaranteed to be initialized first so i can init s2 safely?
2. Is s2 guaranteed to be initialized first so i can call func() safely?
3. Any possible problems?
Advertisement
1) Yes
2) No. It's guaranteed to be initialized before either main() starts or it's first use if it's initialized after main() starts, but if you call foo() for static initialization in another translation unit you don't know if it'll be called before or after s2 is initialized. If you can guarantee all uses of foo() will only occur after main() starts you should be fine.
So you mean its dangerous to use static members of one class in another class static functions, when they are in different translation units?

thanks for your time.

If you can guarantee all uses of foo() will only occur after main() starts you should be fine.


True, but in a large project, it's hard to maintain such guarantees, so I suggest you don't get in the habit of doing this type of thing. If you can avoid having global state, you should prefer that. If you can't avoid it, I like having an initialization function that needs to be called explicitly before you use anything in the class or library (like OpenGL requires you to call glInit(), for instance).

Some other opinions:

  • http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.15
  • http://yosefk.com/c++fqa/fqa.html#fqa-10.15

So you mean its dangerous to use static members of one class in another class static functions, when they are in different translation units?

Pretty much. C++ doesn't guarantee the order the runtime initialization order of different translation units. It can even change from one compile to the next.

This topic is closed to new replies.

Advertisement