如果内存不足,则抛出 bad_alloc

问题描述

/ *
* \ brief Dictionary builder from file
*
* \ pre There is enough memory
* \ pre The file is first opened
*
* \ post If the file is open,the class instance has been initialized from
* from the dictionary file. Otherwise,we generate an empty class.
*
* \ exception bad_alloc if there is not enough memory
* This method calls chargeDicSyn!
* /
DicSyn::DicSyn(std::ifstream &file):
root(0),nbRadicals(0),groupesSynonymes()
{
    chargeDicSyn(file);
}

如果内存不足,我必须抛出异常 bad_alloc。我真的不是专家。我怎样才能用这种方法做到这一点?

解决方法

如果您的代码使用 operator new(或任何使用 operator new 的东西,例如标准库)来分配内存,那么它应该已经抛出 {{1} } 如果内存不足。

编辑:如果它使用 C 风格的内存管理(std::bad_alloc 和朋友),我认为不是,因为您是从 malloc 而不是 { {1}} 就像在 C 中一样,那么您应该检查 std::ifstream 是否返回 FILE*(即分配 malloc 调用的指针为空)并抛出 nullptr如果确实如此。如果由于某种原因你不能这样做,你可以malloc并检查是否std::bad_alloc,虽然这不是万无一失,因为#include <cerrno>不能保证设置{{1 }} 失败。