According to the C ++ 14 standard, non-static member variables are initialized in the order in which they are declared in the class. The code abbreviated below relies on this rule to control the flow function.
class foo { foo(): keep_going{true}, my_thread(&foo::go,this) {} void go() { while(keep_going) check a std::condition_variable and do some work; } bool keep_going; std::thread my_thread; }
Note that keep_going declared before the stream object and must be set to true by the time the stream enters the go function. This is normal and seems to work fine.
However, this is multi-threaded code, and it pays for paranoid, so I have two questions:
1 Can one rely on the initialization order as follows? My real object does not make sense without a workflow, so I want to set it in the constructor.
2 Is it unsafe to give code to others when it relies on relatively obscure things, such as the initialization order?
c ++ c ++ 14
user4650542
source share