STL deque pop_front()是否会自动回收内存? [英] Will STL deque pop_front() automatically recycle memory?
问题描述
我有一个程序,其中收集一些数据并将它们临时存储在双端队列中
I have a program in which I collect some data and store them temporarily in a deque
typedef vector<float> floatVector;
...
floatVector * currRecord;
deque<floatVector *> data;
...
...
for (...)
{
...
currRecord = new floatVector(10);
data.push_back(currRecord);
}
稍后,我想将数据保存到文件
Later, I want to save data to file
while (data.size() > 0)
{
for (int i=0; i < 10; i++)
{
fprintf(fPtr, "%lf\t", data[0]->at(i) );
}
fprintf(fPtr,"\n");
data.pop_front();
}
所以,我的问题是,该程序会导致内存泄漏吗?我使用new
运算符为每个currRecord
向量分配内存. deque pop_front
函数是否会自动回收内存?还是我需要放
So, my question is, will this program cause a memory leak? I use new
operator to allocate memory for each currRecord
vector. Will the deque pop_front
function automatically recycle memory? Or do I need to put
delete [] data[0]
之前
data.pop_front();
?另外,如果data
是向量而不是双端队列,那么一切都一样吗?谢谢!
? Also, if data
is a vector instead of a deque, will everything be the same? Thanks!
推荐答案
您有一个std::deque
指针,每个指针都拥有一个资源(内存).调用pop_front()
将从容器中删除一个指针,但不会释放该指针拥有的内存.由于您使用new
分配了内存,因此您还必须调用delete
.如果容器是std::vector
,则情况不变.
You have a std::deque
of pointers and each pointer owns a resource (memory). Calling pop_front()
will remove a pointer from the container but it doesn't release the memory the pointer owns. Since you allocate the memory with new
you must also call delete
. The situation is unchanged if the container is a std::vector
.
如果更改为std::deque<floatvector>
或类似std::shared_ptr
的智能指针容器,则可以避免内存泄漏.
You could avoid memory leaks if you changed to a std::deque<floatvector>
or a container of smart pointers like std::shared_ptr
.
请注意,调用new
时并没有使用[]
,因此请使用不带方括号的普通delete
.
Note that you didn't use []
when you called new
so use plain delete
without square brackets.
这篇关于STL deque pop_front()是否会自动回收内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!