变量定义期间是否有可能发生异常

is there any chance an exception happens during variable definition?

本文关键字:可能发生 异常 是否 定义 变量      更新时间:2023-10-16
class ThreadGuard {
public:
    ThreadGuard(std::thread &t_): t(t_) {}
    ~ThreadGuard()
    {
        if(t.joinable()) 
            t.join();
    }
private:
    std::thread &t;
};
void func()
{
    std::thread my_thread(f);
    ThreadGuard thread_guard(my_thread);
}

我尝试使用 ThreadGuard 对象来保证 func 在线程正常终止之前不会退出。但是,如果在创建thread_guard对象之前发生异常怎么办?

RAII 的要点是让资源获取对象实际拥有资源。您的ThreadGuard仍然无法保证线程实际上受到保护。你会想要更像的东西:

class ThreadGuard {
    std::thread t;
public:
    ~ThreadGuard() {
        if (t.joinable()) t.join();
    }
    // constructors and assignment as appropriate to actually
    // initialize the thread object
};

这样,你就可以写:

ThreadGuard thread_guard(f);

不用担心。