当我们创建
Queue
对象时,会调用构造函数,如果 Queue
太大,内存分配将失败,构造函数将抛出 std::bad_alloc
错误。
Queue(const int capacity){
try{
arr = new int[capacity];
front = 0, rear = 0;
this->capacity = capacity;
}
catch(const std::bad_alloc& ba){
cerr << "Failed to allocate memory for the queue!" << endl;
}
}
在运行时,用户可以调用某些函数,例如
enqueue()
,但程序只会说Queue
已满,不会做任何有害的事情。在内存分配失败后,有什么方法可以阻止用户在这个 Queue
对象上使用函数。
我尝试创建一个公共函数,仅检查
*arr
是否等于 nullptr
并在我的 Queue
类中的每个函数的开头使用它,但我发现如果我想要为我的 Queue
类创建新函数和太多函数重复。
如果你在构造函数中捕获,你就会使
Queue
变得更难使用。仅当您能够处理异常时才应捕获该异常。这可能是直接调用者使用较小的容量重试,或者是堆栈上更远的位置,在 UI 上显示错误消息。
例如如果插入队列可以扩展它,那么在这种情况下您就引入了未定义行为的可能性:
Queue queue(100); // caller assumes no allocations after this, because that's normal when providing a capacity
queue.push_back(1);
auto iter = queue.begin();
queue.push_back(2); // queue gets expanded, iter is invalidated
std::cout << *iter; // undefined behaviour