The short answer : yes. How? The order of inialization between translation units is not defined, thus the same applies for destruction. The following can happen:
- a global object is constructed before a logger
- thus, it will be destroyed after the logger
- if in its destructor it tries to use the logger, there we go - logger is used after it's been destroyed.
Many thanks to Daniel Kruger for helping me with this:
The way to handle this is: since we can't handle initialization between translation units, we can handle initialization within the same translation unit. In the same translation unit, if we have:
... we're guaranteed a
is initialized before b
. In other words, if in a translation unit a
is defined before b
, a
will be initialized before b
.
Apply this to our problem:
- we just need some object that will reference the logger, to be defined before the global object that might end up using the logger in its destructor
- note: referencing the logger will imply it gets constructed first
- this way, the logger will be created before the global object, and thus be destroyed after it
In every translation unit that has a global object that might end up using logger(s) on its destructor, we need to create some object that will reference those loggers before the global object's definition.
Therefore, the amazing solution:
#define BOOST_DECLARE_LOG(name,type) type* name (); \
namespace { boost::logging::ensure_early_log_creation ensure_log_is_created_before_main ## name ( * name () ); }
When declaring the logger, we create a dummy static - in each translation unit -, that uses the logger; this will ensure the logger is created before the global object that will use it.
All you need to do is :
- #include the header file that declares the logs in all translation units that have global objects that could log from their destructor.
- of course, to be sure, you could #include that header in all translation units :)
- Note:
- This applies to filters as well.
Copyright John Torjo © 2007
Have a question/ suggestion/ comment? Send me feedback