为什么 std::make_unique<std::thread>(somefun()) 会在我没有调用 release() 时生成崩溃,并且在调用时会生成崩溃?

Why std::make_unique<std::thread>(somefun()) will generate crash when I haven't call release(), and well when called?

本文关键字:调用 崩溃 std thread make unique release lt 为什么 gt somefun      更新时间:2023-10-16

我的代码:

{
    t = std::make_unique<std::thread>(std::bind(&Widget::generateNum, this));
}

~thread()崩溃,错误msg是' R6010 APORT((已称为'。如果我在破坏t之前没有打电话给t.release(),则会导致崩溃。

您必须在破坏线程之前分离或加入线程。

auto t = std::make_unique<std::thread>(std::bind(&Widget::generateNum, this));
// Either do this:
t->detach();
// or do this:
t->join();
// before *t gets destroyed.

选择是否分离还是加入取决于您,但您必须必须做一个或另一个。如果非空std::thread被销毁,它将调用std::terminate,结束您的程序。

请参阅std :: thread ::〜线程:

如果*this具有关联线程(joinable() == true(,则称为std::terminate()

默认的std::terminate处理程序调用std::abort,因此已调用流产的消息。

不要致电T.Release((

致电t.release()是错误的。这会泄漏std::thread对象。