我有一個強大的用例來預先分配我需要的所有內存,並在完成時釋放它。C++緩衝池?
我已經出來了這個真正簡單的緩衝池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);
}
};
你忘了'pop_back()'... – 2012-04-05 19:33:55
真的,謝謝:) – 2012-04-05 19:41:25
請,請,請永遠不會調用退出類。拋出異常! – devshorts 2012-04-05 19:47:38