1

Say I create a member variable pointer pBuffer. I send this buffer into some unknown land to be filled with data. Now say pBuffer has an arbitrary amount of data in it.

Q: Is there a way to reset pBuffer without completely deleting it, while still deallocating all unnecessary memory it was occupying?

Example:

class Blah
{
public:

    unsigned char* pBuffer;

    Blah(){pBuffer = NULL;}
    ~Blah(){}

    FillBuffer()
    {
        //fill the buffer with data, doesn't matter how
    }

    ResetBuffer()
    {
        //????? reset the buffer without deleting it, still deallocate memory ?????
    }

};

int main()
{
    Blah b;
    b.FillBuffer();
    b.ResetBuffer();
    b.FillBuffer(); //if pBuffer were deleted, this wouldn't work
}
4

3 回答 3

1

Try realloc() if you know the amount of stuff in the buffer vs the remaining space in the buffer.

于 2013-02-12T21:15:26.317 回答
1

Using only a single raw pointer, no; but if you keep a size variable you can reset the buffer relatively easily.

However, this being tagged as C++, I would like to caution you from doing this and will instead propose an alternative. This meets your requirement of allowing memory to be allocated then later for the buffer to be "reset", without deallocating the memory. As a side benefit, using std::vector means that you don't have to worry about the memory leaking in subsequent calls to FillBuffer(), specifically when the existing buffer is too small and would need to be reallocated.

#include <vector>

class Blah
{
public:

    std::vector<unsigned char> pBuffer;

    Blah(){}
    ~Blah(){}

    FillBuffer()
    {
        //fill the buffer with data, doesn't matter how
    }

    ResetBuffer()
    {
        pBuffer.clear();

        // if you _really_ want the memory "pointed to" to be freed to the heap
        // use the std::vector<> swap idiom:

        // std::vector<unsigned char> empty_vec;
        // pBuffer.swap(empty_vec);
    }
};
于 2013-02-12T21:16:55.977 回答
0

Buffers typically need a maximum size and a current size. To "reset", you would set the current size to zero. When you use it again, you might need to grow or shrink the maximum size of the buffer. Use realloc or malloc/new and memcpy (which realloc does internally when growing) to move existing data to the new buffer.

Note that these are expensive operations. If you expect the buffer to need to grow from use to use, you might consider doubling its maximum size every time. This effectively amortizes the cost of the allocation and copy.

于 2013-02-12T21:18:01.597 回答