Is leaking std::thread undefined behaviour?

后端 未结 3 1518
难免孤独
难免孤独 2021-01-07 14:11

Reason why somebody would be interested in

  //...
 new std::thread (func,arg1,arg2);

}

is that std::thread destructor(unlik

3条回答
  •  日久生厌
    2021-01-07 14:47

    This is not OK according to the final text. Specifically, the destructor of a thread that has been neither joined nor detached will call std::terminate.

    std::thread destructor is not called when the callback returns, but when the thread object goes out of scope, just like any other object. So, a new'd thread that is never delete'd will never be destructed, leaking any associated state (and things potentially going horribly wrong if/when the program terminates with any extra threads still running...)

    To answer your question about lifetimes, std::thread is like std::bind: it stores copies of its arguments and passes those copies to the callback, regardless of whether the callback takes its arguments by value or by reference. You must explicitly wrap arguments with std::ref to get reference semantics. In this case, as usual, it's up to you to ensure that no dangling references occur (for instance by calling thread::join() before any referenced variables go out of scope.)

提交回复
热议问题