Running code outside main() is dubious.
One simple alternative is to make all these objects local to main. Then you can point global pointers at them when they are valid. Before they are destroyed, null out the pointers. To make it safe ensure that all your "global" classes do not use the global pointers to other sub-systems. Instead, they must be passed pointers/references. This way your constructor order will naturally force objects to be constructed in a particular order, and will alert you to circular dependencies (your Logger shouldn't be using the MemoryManager if the MemoryManager wants to use the Logger).
Logger *globalLogger = 0;
MemoryManager *globalMemoryManager = 0;
int main()
{
Logger logger("foo.log");
MemoryManager memoryManager(logger);
// Globals accessed before here will be NULL!
globalLogger = &logger;
globalMemoryManager = &memoryManager;
// Globals are safe!
Application application;
application.run();
// Goodbye globals...
globalLogger = 0;
globalMemoryManager = 0;
}
You may want to export your globals through functions rather than directly as global pointers to prevent accidental assignment:
namespace
{
Logger *globalLogger = 0;
MemoryManager *globalMemoryManager = 0;
}
Logger &logger()
{
assert(globalLogger);
return *globalLogger;
}
MemoryManager &memoryManager()
{
assert(globalMemoryManager);
return *memoryManager;
}
int main()
{
// ...
}