I came across an example of basic std::thread usage from "The C++ programming language" by Bjarne Stroustrup, and it confuses me. Here is the example:
void run(int i, int n) // warning: really poor code
{
thread t1 {f};
thread t2;
vector<Foo> v;
// ...
if (i<n)
{
thread t3 {g};
// ...
t2 = move(t3); // move t3 to outer scope
}
v[i] = Foo{}; // might throw
// ...
t1.join();
t2.join();
}
As Stroustrup writes:
we may never reach the two
join()s at the end. In that case, the destructor fort1will terminate the program.
But, in which case is t1's destructor called? The t1 thread is not going out of its scope. There is no explicit delete call, either.
I tried to run this code with appropriate changes, but still I couldn't find how t1's destructor is being called.
runreturns the local variables get out of scope and are destroyed (and the destructor fort1etc. is called).run()will never return, and locally constructed objects never destroyed) the only things that can happen to cause thejoin()s to be never reached are an exception being thrown (possibly by a called function) or areturnstatement in preceding code withinrun(). In both cases, all locally constructed objects (of automatic storage duration) are destroyed, in reverse order of their construction, and their destructors called/invoked. Sincet1is constructed beforet2, it is destructed last.