【发布时间】:2015-07-21 12:33:23
【问题描述】:
在没有例外的情况下,我看到几个帖子说
Thing* t = new(std::nothrow) Thing; // returns NULL on failure
if (!t) {
// allocation failure
}
例如
How to check memory allocation failures with new operator?
How to find out the return value if my C++ “new” memory allocation failure?
我相信这是他们从 C++ 标准中得到的声明,如引用:
如果分配函数声明为非抛出 exception-specification ,它返回 null 表示失败 否则分配存储空间和非空指针。
然而,赫伯·萨特 http://www.gotw.ca/publications/mill16.htm
linux 会过度使用内存,这不符合 c++ 标准。即,检查 null 与 linux 系统无关。 “new”要么成功,要么失败,进程被 linux 杀死。
那么我们能做些什么呢?似乎没有办法检查故障。
[更新] 关于 linux overcommit:overcommit_memory
0 — 默认设置。内核执行启发式记忆 通过估计可用内存量和 明显无效的失败请求。不幸的是,由于 内存是使用启发式而不是精确算法分配的, 此设置有时可以允许系统上的可用内存 重载。
【问题讨论】:
-
Herb Sutter 的链接页面是 2001 年的。您确定没有更新的文档吗?另外,我是一个说,如果 new/malloc 失败,你会遇到比考虑如何处理更大的问题。只要让应用程序被杀死就可以了。
-
我不确定,这就是我问的原因,:-)
-
Linux OOM 杀手杀死 其他 进程以使用它们的内存来分配它的进程。正如页面所指出的,
malloc和其他分配函数永远不会因内存过度使用而失败(除非他们这样做,但它会以标准方式处理),因此没有“失败”需要检查。
标签: c++ linux memory-management new-operator nothrow