如何“重置”缓冲区?

时间:2013-02-12 21:12:48

标签: c++ pointers memory buffer

假设我创建了一个成员变量指针pBuffer。我将这个缓冲区发送到一些未知的土地上以填充数据。现在说pBuffer中有任意数量的数据。

问:有没有办法在不完全删除pBuffer的情况下重置pBuffer,同时仍然取消分配它占用的所有不必要的内存?

示例:

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
}

3 个答案:

答案 0 :(得分:1)

如果您知道缓冲区中的内容数量与缓冲区中的剩余空间数量,请尝试realloc()

答案 1 :(得分:1)

仅使用一个原始指针,不;但如果你保留一个大小变量,你可以相对容易地重置缓冲区。

但是,这被标记为C++,我想提醒您这样做,而是提出替代方案。这符合您的要求,即允许分配内存,然后将缓冲区“重置”,而不释放内存。作为附带好处,使用std::vector意味着不必担心后续调用FillBuffer()时内存泄漏,特别是当现有缓冲区太小时需要重新分配。

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

答案 2 :(得分:0)

缓冲区通常需要最大大小和当前大小。要“重置”,您可以将当前大小设置为零。再次使用它时,可能需要增大或缩小缓冲区的最大大小。使用reallocmalloc / newmemcpy(realloc在增长时在内部执行)将现有数据移至新缓冲区。

请注意,这些都是昂贵的操作。如果您希望缓冲区需要从使用增长到使用,您可能会考虑每次将其最大大小加倍。这有效地分摊了分配和复制的成本。

相关问题