变量定义期间是否有可能发生异常
is there any chance an exception happens during variable definition?
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);
不用担心。
相关文章:
- 构造函数中发生异常时如何释放 API 使用的资源
- 如果在构造函数中发生异常,如何释放动态内存
- 为什么初始化构造函数列表参数时会发生异常?
- 在多线程中是否可能发生读取对象的一半大小?
- 如何在 VS C++ 中查找发生异常的位置
- 从可能引发异常的函数返回 std::string
- 私有成员"current"的值在成员函数结束时发生异常更改
- 如果发生异常,则在不使用异常时返回非流动函数的返回?C
- 在scoped_ptr发生异常的情况下未调用析构函数
- 如何在发生异常时运行代码
- C++读取文件时可能发生内存泄漏
- std::out_of_range在字符串向量中搜索匹配项时发生异常
- std::启动服务器时发生异常(WinSock2)
- 变量定义期间是否有可能发生异常
- while(true)可能发生的最坏情况是什么?
- C++:为什么我会出现此分段错误(可能发生在 main 之前?
- 在发生异常时从 std 容器释放内存的策略bad_alloc
- 通过boost::read_graphviz()读取boost动态属性时发生异常
- std::使用来自本地对象的消息时发生异常
- sscanf上可能发生溢出