简体   繁体   中英

bad_alloc with QVector but not with std::vector

I guess it's not so much a question but a request for comments.

Today I was trying to load a larger dataset into my software and encountered a couple of bad allocs.

So the code in question looks like this.

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

numPoints in this case is 92911773 so it'll try to allocate numpoints * 6 * sizeof( float ) = 2,214,922,152 bytes. My machine runs a 64bit linux with 12Gb ram. So this shouldn't be a problem.

So this throws the bad_alloc exception. Now if I change the QVector to an std::vector it works. Can anyone comment on this?

Without looking at the definition of QVector , I'm going to guess that it is because Qt uses an int to represent the size.

Your vector's size is big enough that an int will overflow, so the allocation fails.

std::vector does the correct (and sane) thing, and uses a size_t to represent the size, so it doesn't overflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM