bad_alloc::`标量删除析构函数'(unsigned int) 当我试图创建一个 470mb 大小的向量时

bad_alloc::`scalar deleting destructor'(unsigned int) when im trying to create a vector 470mb size

在这种情况下最有趣的是,昨天它工作正常。 我不知道是什么原因造成的麻烦

size = 480 000 000;
std::vector<char> result(size);

Vector 尝试分配所需大小的连续 内存块。根据系统内存碎片,可能没有 0.5Gb 块可用,内存分配失败。

您正在分配大量连续内存,因此如果您 运行 内存不足,您将获得 bad_alloc。

The most interesting in this case, that yesterday it's work okay.

一个std::vector的内容不是凭空存储的;它们占用您计算机中的内存。显然,您计算机中的内存情况一直在变化。从昨天开始可用的总可用 space 变小了,或者现在有更多碎片,因此即使总可用 space 远远超过 470MB,也没有可用的 连续 470MB spot anywhere.

也许 std::deque 可以在短期内足够优雅地解决问题:

As opposed to std::vector, the elements of a deque are not stored contiguously: typical implementations use a sequence of individually allocated fixed-size arrays, [...]

当然,正如同一文档所解释的那样,这有一些缺点。