Destroying a std::thread
object associated with a joinable()
thread causes std::terminate()
to be called. §30.3.1.3 [thread.thread.destr]:
~thread();
If
joinable()
, callsstd::terminate()
. Otherwise, has no
effects. [ Note: Either implicitly detaching or joining ajoinable()
thread in its destructor could result in difficult to debug
correctness (for detach) or performance (for join) bugs encountered
only when an exception is raised. Thus the programmer must ensure that
the destructor is never executed while the thread is still joinable.
—end note ]
There are a multitude of possible fixes:
- Allocate the thread on the heap and having your function return a smart pointer to the thread object
- Or have it return a
std::thread
(moveserverConnect
into the return value) - Move
serverConnect
into something that won’t be destroyed whenconnectToServer()
returns (e.g., a global variable) join()
the thread before you returndetach()
the thread before you return
The correct choice depends on your particular use case.