Global Initialization

closed account (S6k9GNh0)
In C, this doesn't work... but in C++, we can use a translation unit to automatically initialize a class instance. As a result, you'll find some libraries using this to initialize so as to remove the need for the user to do so himself. My question is what are the options when it comes to error checking for this? Can we throw exceptions? And if so, how do we catch them so they can be handled by the user (and so we can de-initialize anything we need too..)? Also, is there any standard when it comes to order of initialization?
Last edited on
Are you looking for a singleton?
closed account (S6k9GNh0)
Similar to one yeah, but a global object is supposedly "better" which I can see where, I just don't understand how you perform error checking properly.
Constructors shouldn't throw exceptions, and the order of initialization of global objects is undefined.
Just my opinion, but if you're doing any kind of initialization before main(), it shouldn't be throwing an exception.

I prefer to initialize my libraries in main
closed account (S6k9GNh0)
I see. SFML does initialization via global. Also, most anti-singleton persons will suggest that you use globals instead of singletons. I think a global would be much cleaner imo but it doesn't seem like it would work out... C++ also has no standard as far as singletons goes either which doesn't make it easier. Boost contributors and sandbox help though...

http://www.torjo.com/tobias/

By the way, why shouldn't exceptions be thrown in constructor? I've read two books all of which suggest exceptions (if applicable) as long as the mess is cleaned before the exception is thrown. This, especially when the class is vital such as an engine of some sort, makes things a lot easier in certain cases.
Last edited on
Actually, never mind. It was destructors that weren't supposed to throw exceptions.
Last edited on
Singletons have a well-deserved bad rap because a lot of developers used singleton not just as a means to enforce "one and only one" semantics where required for program correctness, but abused it for object lifecycle management in general: I only need one of these, so let's make this class a singleton. This makes the class unnecessarily difficult to test and prevents its use in certain multi-threaded designs.

However, used properly, Singleton is the best solution for the problem it was designed to solve.
Topic archived. No new replies allowed.