Will STL deque pop_front() automatically recycle memory?

天大地大妈咪最大 提交于 2019-12-08 07:22:12

问题


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();
    }

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]

before

    data.pop_front();

? Also, if data is a vector instead of a deque, will everything be the same? Thanks!


回答1:


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.

You could avoid memory leaks if you changed to a std::deque<floatvector> or a container of smart pointers like std::shared_ptr.

Note that you didn't use [] when you called new so use plain delete without square brackets.



来源:https://stackoverflow.com/questions/11554083/will-stl-deque-pop-front-automatically-recycle-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!