Is this normal behavior for a std::vector?

前端 未结 3 1229
不思量自难忘°
不思量自难忘° 2021-01-16 03:40

I have a std::vector of a class called OGLSHAPE.

each shape has a vector of SHAPECONTOUR struct which has a vector of float and a vector of vector of double. it also

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-16 03:54

    There are a few possible things at play here.

    First, the way memory works in most common C and C++ runtime libraries is that once it is allocated to the application from the operating system it is rarely ever given back to the OS. When you free it in your program, the new memory manager keeps it around in case you ask for more memory again. If you do, it gives it back for you for re-use.

    The other reason is that vectors themselves typically don't reduce their size, even if you clear() them. They keep the "capacity" that they had at their highest so that it is faster to re-fill them. But if the vector is ever destroyed, that memory will then go back to the runtime library to be allocated again.

    So, if you are not destroying your vectors, they may be keeping the memory internally for you. If you are using something in the operating system to view memory usage, it is probably not aware of how much "free" memory is waiting around in the runtime libraries to be used, rather than being given back to the operating system.

    The reason your memory usage increases slightly (instead of not at all) is probably because of fragmentation. This is a sort of complicated tangent, but suffice it to say that allocating a lot of small objects can make it harder for the runtime library to find a big chunk when it needs it. In that case, it can't reuse some of the memory it has laying around that you already freed, because it is in lots of small pieces. So it has to go to the OS and request a big piece.

提交回复
热议问题