这是std :: vector的正常行为吗? [英] Is this normal behavior for a std::vector?

查看:147
本文介绍了这是std :: vector的正常行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为OGLSHAPE的类的std :: vector。

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

每个形状都有一个SHAPECONTOUR结构的向量,它有一个float的向量和一个向量的vector的双。它也有一个大纲结构的向量,它有一个浮动的向量。

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

最初,我的程序使用8.7 MB的RAM启动。我注意到,当我开始填充这些,除了加倍和浮动,内存很快相当高,然后平息。当我清除OGLSHAPE向量时,仍然使用大约19MB。然后,如果我推大约150个形状,然后清除那些,我现在使用大约19.3MB的ram。我会认为,从逻辑上来说,如果第一次从8.7到19,下一次它会上升到30左右。我不知道是什么。我认为这是一个内存泄漏,但现在我不知道。我所做的是将数字推入std ::向量,没有别的。所以我希望得到我的记忆回来。这可能会导致什么?

Initially, my program starts up using 8.7 MB of ram. I noticed that when I started filling these these up, ex adding doubles and floats, the memory got fairly high quickly, then leveled off. When I clear the OGLSHAPE vector, still about 19MB is used. Then if I push about 150 more shapes, then clear those, I'm now using around 19.3MB of ram. I would have thought that logically, if the first time it went from 8.7 to 19, that the next time it would go up to around 30. I'm not sure what it is. I thought it was a memory leak but now I'm not sure. All I do is push numbers into std::vectors, nothing else. So I'd expect to get all my memory back. What could cause this?

感谢


*编辑,
从分配很多小东西,
如何解决?

*edit, okay its memory fragmentation from allocating lots of small things, how can that be solved?


推荐答案

调用std :: vector<> :: clear()不一定释放所有分配的内存(它取决于std :: vector<>的实现)。这通常是为了优化的目的,以避免不必要的内存分配。

Calling std::vector<>::clear() does not necessarily free all allocated memory (it depends on the implementation of the std::vector<>). This is often done for the purpose of optimization to avoid unnessecary memory allocations.

为了真正释放实例持有的内存,只需:

In order to really free the memory held by an instance just do:

template <typename T>
inline void really_free_all_memory(std::vector<T>& to_clear)
{
    std::vector<T> v;
    v.swap(to_clear);
}

// ...
std::vector<foo> objs;

// ...
// really free instance 'objs'
really_free_all_memory(objs);

这将创建一个新的(空)实例,并将其与您要清除的矢量实例交换。

which creates a new (empty) instance and swaps it with your vector instance you would like to clear.

这篇关于这是std :: vector的正常行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆