对象池设计与实现

#include 
#include 
#include 
#include 

using namespace std;

#define BLOCK_SIZE 10

template 
class MemPool {
public:
    MemPool() {
    }
public:
    static T* get_object() {
        if (!_free_blocks.empty()) {
            T* top = _free_blocks.top();
            _free_blocks.pop();
            return top;
        }
        T* obj = nullptr;
        if (_cur_block && _cur_block->nitem < BLOCK_SIZE) {
            obj = new ((T*)_cur_block->blocks + _cur_block->nitem) T;
            ++_cur_block->nitem;
            return obj;
        } else {
            Block* block = new (std::nothrow)Block;
            _cur_block = block;
            cout << "_cur_block->nitem= " << _cur_block->nitem << endl;
            obj = new ((T*)(_cur_block->blocks) + _cur_block->nitem) T;
            ++_cur_block->nitem;
        }
        return obj;
    }
    static void return_object(T* obj) {
        _free_blocks.push(obj);
    }
class Block {
public:
    Block() {
        nitem = 0;
    }
    char blocks[sizeof(T)*BLOCK_SIZE];
    int nitem;
};
    static Block* _cur_block;
    static std::stack _free_blocks;
};
template 
typename MemPool::Block* MemPool::_cur_block = nullptr;
template 
typename std::stack MemPool::_free_blocks;


class Test{
public:
    Test() {
        cout << "Test()" << endl;
    }
    ~Test() {
        cout << "~Test()" << endl;
    }
};

int main() {
    std::vector objs;
    for (int i = 0; i < BLOCK_SIZE+1; ++i) {
        objs.push_back(MemPool::get_object());
    }
    for (int i = 0; i < BLOCK_SIZE-1; ++i) {
        objs.push_back(MemPool::get_object());
    }
    for (int i = 0; i < BLOCK_SIZE+1; ++i) {
        MemPool::return_object(objs[i]);
    }
    for (int i = 0; i < BLOCK_SIZE+1; ++i) {
        objs.push_back(MemPool::get_object());
    }
}

1.new 重载placement new

2.栈,使用最近归还的对象,进行对象池对象分配

3.静态对象需要在类外进行初始化

你可能感兴趣的:(C++奇技淫巧,C++内存管理,c++,算法,开发语言)