简体   繁体   English

在C ++中删除和释放向量内存的正确方法(防止与内存相关的错误)

[英]Proper way to delete and free up memory of a vector (prevent different memory related errors) in c++

creating a vector: 创建向量:

std::vector<int> pqrs;

delete in proper way to free up all memory (prevent memory leaks and other memory related issues) inside the function: 以适当的方式删除以释放函数内的所有内存(防止内存泄漏和其他与内存相关的问题):

pqrs.clear();
std::vector<int>().swap(pqrs);

My question is: both clear and swap required (say for calling destructor)? 我的问题是:既需要清除又需要交换(例如调用析构函数)? or swap is sufficient for all purpose. 或交换足以满足所有目的。

In case of std::vector<int> you don't need to do either clear() nor swap to free memory, because elements of std::vector<int> here ( int s) are automtically allocated and freed by the std::vector<int> methods anddestructor. std::vector<int>情况下,您无需执行clear()swap到空闲内存,因为std::vector<int>元素( int s)是由std::vector<int>自动分配和释放的std::vector<int>方法和析构函数。 Data will be freed at the end of scope (function or program). 数据将在作用域(功能或程序)的末尾释放。

Hence,answer to your question would be, You don't need to call clear or swap . 因此,您的问题的答案将是:您不需要调用clearswap

Since vector<int> object in above question is a variable with automatic storage - so it will be automatically destroyed when it goes out of scope. 由于上述问题中的vector<int>对象是具有automatic存储的变量-因此,超出范围时将被自动销毁。 And when a container object goes out of scope, it's destructor is called which in-turn frees up space used for storage of contained elements and during this step destructor for all contained elements also gets invoked (in case of user-defined types). 当容器对象超出范围时,将调用其析构函数,该析构函数进而释放用于存储所包含元素的空间,并且在此步骤中,还将针对所有所包含元素调用析构函数(在用户定义类型的情况下)。 So, if we have just plan int elements, no need to do anything extra. 因此,如果我们仅计划int元素,则无需执行任何其他操作。 But we would have memory leak if contained type if T* where T is some user-defined type because in that case destructor wouldn't be called explicitly for pointed-to objects. 但是如果如果T*包含类型,则我们将发生内存泄漏,其中T是某些用户定义的类型,因为在这种情况下,不会为指向对象显式调用析构函数。

Your phrase about memory leaks makes the whole meaning of the question unclear. 您关于内存泄漏的说法使问题的整体含义不清楚。 When the vector goes out of scope, the memory is released. 当向量超出范围时,将释放内存。 There should be no memory leak. 应该没有内存泄漏。

In major projects, it is fairly common to need a vector to release its allocation at a certain point before it goes out of scope. 在大型项目中,通常需要一个向量在超出范围之前在某个点释放其分配。 Failure to do so is not a memory leak but may be a problem. 失败不是内存泄漏,而是一个问题。 For that purpose, .clear() is useless. 为此, .clear()是无用的。 The swap approach you suggested (without the .clear ) works. 您建议的swap方法(不带.clear )有效。 I don't know a way to do it without swap . 没有swap我不知道有什么办法。

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

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