c++ - How to know if the main() is running? -
context : in application, have functions using global variables. due undefined order of allocation of global variables, want forbid call these functions before main
function running. moment, document \attention
in doxygen, add assertion.
my question : is there elegant way know main
function not running yet ?
example (uniqid.cpp):
#include <boost/thread.hpp> #include <cassert> unsigned long int uid = 0; boost::mutex uniqid_mutex; unsigned long int uniquid() { assert(main_is_running() && "forbidden call before main running"); boost::mutex::scoped_lock lock(uniqid_mutex); return ++uid; }
my first (ugly) idea : first idea checking global variable specific value. probability have value in variable before initialisation small :
// file main_is_running.h void launch_main(); bool main_is_running(); // file main_is_running.cpp unsigned long int main_is_running_check_value = 0; void launch_main() { main_is_running_check_value = 135798642; } bool main_is_running() { return (main_is_running_check_value == 135798642); } // file main.cpp #include "main_is_running.h" int main() { launch_main(); // ... return 0; }
is there better way ?
note can't use c++11 because have compatible gcc 4.1.2.
if static std::atomic<bool> s;
defined, along little toggling struct
:
struct toggle { toggle(std::atomic<bool>& b) : m_b(b) { m_b = true; } ~toggle() { m_b = false; } std::atomic<bool>& m_b; };
then, in main
, write toggle t(s);
first statement. 1 of instances having reference member variable idea.
s
can tell if you're in main
or not. using std::atomic
overkill given behaviour of main
calling undefined in c++. if don't have c++11, volatile bool
adequate: effectively not in main
until statement has completed.
Comments
Post a Comment