在发生异常时从 std 容器释放内存的策略bad_alloc
strategy to free memory from std container in case of bad_alloc exception
我正在考虑实施以下策略:
在类方法中处理std::bad_alloc
异常时,在重新引发异常之前,将尽可能尝试释放内存/有意义。因此,如果一个对象有一些可以释放的 std 容器 (std::vector<>),那么我们可以执行以下操作:
catch( std::bad_alloc& e ) {
//free any memory in my std::vector member, how? by doing this dirty hack
~myVec();
new ( &myVec) std::vector<myType>();
throw; //rethrow exception
}
问题:上述"肮脏黑客"是否是一种在异常展开时释放内存的安全策略? 有什么优点和缺点?
你不需要
做任何这样的事——向量将被自动破坏。这就是 RAII 的工作方式。即使您希望在其他情况下清除矢量,它也带有一种clear()
方法。或者你可以做vec = std::vector<T>();
.
相关文章:
- 包含矢量指针的结构的内存释放问题
- Valgrind 声称内存释放中的自由空间太多
- 当 C 和 C++ 中严格要求内存释放时
- C++ 中指针变量的内存释放
- 德克内存释放
- 临时对象 c++ 的内存释放
- C 全局对象变量内存释放
- C++矢量动态内存释放/删除
- 从 cv::Mat 初始化的 IplImage 的内存释放
- SWIG类型映射中的内存释放
- STL容器中的内存释放
- QWebView内存释放
- 内存释放 C++
- 大返回值(如字符串)的内存释放如何在C++中发生
- 重新分配之前的内存释放
- Linux C++ 中的内存释放
- VS2012编译器奇怪的内存释放问题
- 调试断言失败!错误的内存释放
- 负责 COM 互操作中的内存释放
- imread命令后OpenCV矩阵内存释放