我有一个强大的用例,可以预先分配我需要的所有内存,并在完成时释放它。

我已经提出了这个真正简单的缓冲池C++实现,我必须对其进行测试,但是我不确定我尝试使用的指针算法是否可以做到这一点。基本上,我接下来要做的是发布。我希望围绕这个想法有一些技巧,而不是依赖于任何种类的内存处理程序,这只会使客户端代码更复杂。

#include <stdio.h>
#include <queue>

#include "utils_mem.h"

using namespace std;

template <class T>
class tbufferpool {
private:
    const int m_initial;
    const int m_size;
    const int m_total;
    T*        m_buffer;
    vector<T*> m_queue;

public:
    // constructor
    tbufferpool(int initial, int size) : m_initial(initial), m_size(size), m_total(initial*size*sizeof(T)) {
        m_buffer = (T*) malloc(m_total);
        T* next_buffer = m_buffer;
        for (int i=0; i < initial; ++i, next_buffer += i*size) {
            m_queue.push_back(next_buffer);
        }
    }

    // get next buffer element from the pool
    T* next() {
        // check for pool overflow
        if (m_queue.empty()) {
            printf("Illegal bufferpool state, our bufferpool has %d buffers only.", m_initial);
            exit(EXIT_FAILURE);
        }
        T* next_buffer = m_queue.back();
        m_queue.pop_back();
        return next_buffer;
    }

    // release element, make it available back in the pool
    void release(T* buffer) {
        assert(m_buffer <= buffer && buffer < (buffer + m_total/sizeof(T)));
        m_queue.push_back(buffer);
    }

    void ensure_size(int size) {
        if (size >= m_size) {
            printf("Illegal bufferpool state, maximum buffer size is %d.", m_size);
            exit(EXIT_FAILURE);
        }
    }

    // destructor
    virtual ~tbufferpool() {
        free(m_buffer);
    }
};

最佳答案

首先,增加指向T的指针时,它将指向内存中T的下一个元素。

m_queue.push(m_buffer + (i*size*sizeof(T)));

这应该像
m_buffer = (T*) malloc(m_total);
T* next = m_buffer;
for (int i=0; i < initial; ++i) {
    m_queue.push(next++);
}

第二,
assert(m_buffer <= buffer && buffer < m_total);

应该像
assert(m_buffer <= buffer && buffer <= m_buffer + m_total/sizeof(T));

希望能帮助到你!

关于c++ - C++缓冲池?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10034839/

10-13 07:00