Sunday, October 7, 2007

static Initialization Order Fiasco

So I haven't posted on here in quite some time, but I wanted to post about something I learned this week. It's called the "static initialization order fiasco" and it's pretty crazy. First off I always remember that "static is evil" and try to avoid it, but I was helping someone else try and debug a problem and they had used a bunch of C++ fanciness (returning references to static variables inside a static member function) to "hide" the use of global variables and it was coming back to bite them. At first I thought that it must have been some memory problem that they were incorrectly using/overwriting memory, but it ended up being this. It's pretty crazy what types of messes that people can get themselves into when they're trying to be "fancy" but real don't know what they're doing.

Also, I love that "lite" FAQ by the way. It's always got GREAT information and it's usually very well written and very clear. Anytime I have a question about C++, syntax, or odd problems that's the first place I look.

2 comments:

Brad said...

Static is evil!

Also, do you own "The C++ Programming Language" by Bjarne Stroustrup? You probably already do, but if not, it's a wise purchase.

Dave Johansen said...

I agree. static is most definitely evil and this just reaffirmed in my mind that it can always come back to bite you in the butt when you least expect it.

But the craziest part of that code was that the guy had used static variables in static member functions to "hide" the fact that he was using global variables. It was definitely one of those cases where someone tries to get fancy and show off their programming skills, but just ends up creating an ugly unmaintainable mess.