我想编写对内存不足有一定抵抗力的代码。我的尝试是,如果任何内存分配失败,它将暂停执行,并询问操作员是否可以在重新尝试分配之前尝试释放一些内存(或者如果证明不可能,他们可以选择自己终止程序,这取决于他们)
到目前为止,我的代码看起来很丑陋。这是执行任何可能扩展数组的 std::vector 操作的块:
while(pointVector.size() == pointVector.capacity){
// will not break past this if the while statement remains true
// ERROR.report() has the power to kill the program if it needs to
try{
pointVector.reserve(pointVector.capacity * 2); // edited
}catch(...){
ERROR.report(Error::Severity::Memory
, __LINE__, __FILE__
, "Failed to allocate enough points"
, pointVector.size(), 0, 0);
}
}
pointVector.push_back(point);
该ERROR
对象专门预先分配了它的所有资源,因此它可以询问操作员而不会引起任何新问题(理论上)。我的问题是,这可以采取更好的形式吗?对于这种情况,C++ 是否有“重试”逻辑?或者这几乎是应该的?