在发生异常时从 std 容器释放内存的策略bad_alloc

strategy to free memory from std container in case of bad_alloc exception

本文关键字:内存 释放 策略 bad alloc 异常 std      更新时间:2023-10-16

我正在考虑实施以下策略:

在类方法中处理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>();.