简体   繁体   English

如果没有堆内存,如何释放std :: vector

[英]How to release std::vector if there is no heap memory

I have a class member variable like this: 我有一个这样的类成员变量:

vector<vector<int> >  m_stacks;

When I populate it, I do like this: 当我填充它时,我喜欢这样:

vector<int> v;
v.push_back(1);
v.push_back(2);
m_stacks.push_back(v);
vector<int> v2;
v2.push_back(1);
v2.push_back(2);
m_stacks.push_back(v2);

Now I am wondering what I should do in the class destructor to release m_stacks . 现在我想知道我应该在类析构函数中做什么来释放m_stacks I do not allocate any heap memory for it, so I am struggling if I really need to do anything. 我没有为它分配任何堆内存,所以如果我真的需要做任何事情我就会挣扎。 Finally I come up this - 最后我来了 -

vector<vector<int> >::iterator itr = m_stacks.begin();
for ( ; itr != m_stacks.end(); ++itr) {
  itr->clear();
}

I think this is the most I need to do, I do not need to call m_stacks.clear() . 我认为这是我需要做的最多,我不需要调用m_stacks.clear() The reason is vector's destructor can automatically release the memory. 原因是vector的析构函数可以自动释放内存。 But I still need the above code though, the reason is vector's destructor does not call its element's destructor. 但是我仍然需要上面的代码,原因是vector的析构函数不调用它的元素的析构函数。

Could you confirm my call? 你能确认我的电话吗?

You don't have to do anything for m_stacks (a class data member). 您不必为m_stacksclass数据成员)执行任何操作。 Acquired memory will be released automatically when the class destructor will be called. 当调用class析构函数时,将自动释放获取的内存。 This is the purpose for which std::vector is used. 这是使用std::vector的目的。

The destructor for a vector will do two things: it will destroy each element of the vector, then it will free the memory used for the vector itself. 向量的析构函数将执行两项操作:它将销毁向量的每个元素,然后它将释放用于向量本身的内存。 This is automatic. 这是自动的。

In your case you have vectors nested two deep, but it doesn't matter. 在你的情况下,你有两个嵌套的矢量,但没关系。 When the top level vector is destroyed it will call the destructor for each vector it contains, and all of those vectors will clean themselves up properly. 当顶层向量被破坏时,它将为它包含的每个向量调用析构函数,并且所有这些向量将正确地清理它们自己。

The std::vector destructor calls a delete on the memory it allocates, thereby calling that types (in this instance, a std::vector<int> 's) destructor. std::vector析构函数在它分配的内存上调用delete,从而调用那些类型(在本例中为std::vector<int>的)析构函数。

These data structures all rely on SBRM (Scope bound resource management), or RAII (Resource acquisition is initialisation) principles, in that all memory they allocate is de-allocated once they go out of scope (such as the scope of a class). 这些数据结构都依赖于SBRM(范围绑定资源管理)或RAII(资源获取是初始化)原则,因为它们分配的所有内存一旦超出范围(例如类的范围)就会被解除分配。

You do not need to worry about the releasing of memory from a std::vector unless it holds a type which points to memory; 你不需要担心从std::vector释放内存,除非它拥有一个指向内存的类型; but does not release it inherently (such as a pointer!). 但不会固有地释放它(例如指针!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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