Jump to content
  • Advertisement
Sign in to follow this  
belfegor

Static members

This topic is 2256 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!