gpt4 book ai didi

c++ - bad_alloc 与 QVector 但不是与 std::vector

转载 作者:太空宇宙 更新时间:2023-11-04 11:45:53 25 4
gpt4 key购买 nike

我想这与其说是个问题,不如说是征求意见。

今天,我试图将更大的数据集加载到我的软件中,但遇到了一些错误的分配。

所以有问题的代码看起来像这样。

QVector<float>verts;
try
{
verts.reserve( numPoints * 6 );
}
catch ( std::bad_alloc& )
{
qDebug() << "error";
}

本例中的 numPoints 为 92911773,因此它将尝试分配 numpoints * 6 * sizeof( float ) = 2,214,922,152 字节。我的机器运行 64 位 linux 和 12Gb 内存。所以这应该不是问题。

所以这会抛出 bad_alloc 异常。现在,如果我将 QVector 更改为 std::vector ,它就可以工作了。有人可以对此发表评论吗?

最佳答案

如果不看 QVector 的定义,我会猜测这是因为 Qt 使用 int 来表示大小。

您的 vector 大小足以使 int 溢出,因此分配失败。

std::vector 做了正确(和理智)的事情,并使用 size_t 来表示大小,因此它不会溢出。

关于c++ - bad_alloc 与 QVector 但不是与 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19858567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com