C++ C++;分离的线程在其关联对象被删除后继续工作

C++ C++;分离的线程在其关联对象被删除后继续工作,c++,multithreading,C++,Multithreading,在一个作用域中,我创建了一个对象,其中包含一个线程。线程在对象c-tor中分离。最后,我删除了对象,但在关联的对象内存被释放后,线程仍在继续。分离的线程是保存对象副本,还是只引用程序堆栈,程序堆栈将被进一步删除 struct test_detach { test_detach() : thr_(&test_detach::loop, this) { thr_.detach(); } void loop() { while(

在一个作用域中,我创建了一个对象,其中包含一个线程。线程在对象c-tor中分离。最后,我删除了对象,但在关联的对象内存被释放后,线程仍在继续。分离的线程是保存对象副本,还是只引用程序堆栈,程序堆栈将被进一步删除

struct test_detach {
    test_detach()
    : thr_(&test_detach::loop, this) {
        thr_.detach();
    }

    void loop() {
        while(true) {
            cout << "loop test" << endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
    }

    std::thread thr_;
};

int main()
{
    {
        test_detach *test = new test_detach;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        delete test;
    }
    cout << "Sleep" << endl;;
    std::this_thread::sleep_for(std::chrono::seconds(3));

    cout << "Finish!" << endl;;

    return 0;
}

线程一直在运行,直到程序终止。您的线程不使用特定
test\u detach
结构的任何数据字段,因此不存在SEGFAULT。但是,如果将成员变量添加到结构中,并在从主线程删除结构后尝试从分离的线程访问它,则可能会导致SEGFAULT/undefined行为等。
test_detach
结构位于堆上。它不会被复制到任何地方,这是一种观点。然而:

void loop() {
   int x = 0;
    while(true) {
        cout << "loop test, x: " << x++ << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}
void循环(){
int x=0;
while(true){

难道你不应该将不访问任何类成员的成员函数声明为静态的吗?这也让你明白为什么线程可以继续运行,而不关心你是否删除了对象。线程将自动停止的想法是错误的。我在堆栈和堆(如上面的代码中所示)。因此,重点不在于参与的类成员,它们将在对象内存释放后被删除。谢谢!
void loop() {
   int x = 0;
    while(true) {
        cout << "loop test, x: " << x++ << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}