但是目前为止,我编写的代码似乎非常丑陋。以下是在任何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++是否具有针对这种情况的“重试”逻辑?还是这基本上就是该怎么做的?
aligned_storage
。对于之前的混淆,我很抱歉。 - syamstd::set_new_handler
来设置一个回调函数,在重试分配或允许其失败之前,请求更多的内存。 - Blastfurnace