微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果内存不足,则抛出 bad_alloc

如何解决如果内存不足,则抛出 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 }} 失败。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。