Will STL deque pop_front() automatically recycle m

2019-06-03 04:59发布

问题:

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.