一个实现缓冲区BUF管理的模板类

template<class T> class SharedBuffer {
public:
    typedef T* ObjectPointer;
    SharedBuffer(const SharedBuffer& rhs):
        buffer_size(rhs.buffer_size), buffer_pointer(nullptr)
    {
        create_buffer();
        memcpy(buffer_pointer, rhs.buffer_pointer, sizeof(T) * buffer_size);
    }

    SharedBuffer& operator= (const SharedBuffer& rhs) {
        if(this == &rhs) {
            return *this;
        }

        buffer_size = rhs.buffer_size;
        if(buffer_pointer) {
            delete[] buffer_pointer;
            buffer_pointer = nullptr;
        }

        create_buffer();
        memcpy(buffer_pointer, rhs.buffer_pointer, sizeof(T) * buffer_size);
    }

    explicit SharedBuffer(const unsigned short size):
        buffer_size(size), buffer_pointer(nullptr)
    {
            create_buffer();
    }

    ObjectPointer operator()()const {
        return buffer_pointer;
    }

    ~SharedBuffer() {
        if(buffer_pointer) {
            delete[] buffer_pointer;
            buffer_pointer = nullptr;
        }
    }

    const unsigned short size() const {
        return buffer_size;
    }

protected:
    void create_buffer() {
        if(nullptr == buffer_pointer) {
            buffer_pointer = new T[buffer_size];
        }

        buffer_zero();
    }

    void buffer_zero() {
        if(nullptr != buffer_pointer) {
            memset(buffer_pointer, 0x00, sizeof(T) * buffer_size);
        }
    }

private:
    unsigned short buffer_size;
    ObjectPointer  buffer_pointer;
};

 

posted @ 2019-07-05 12:51  日月王  阅读(230)  评论(0编辑  收藏  举报