对象池


smartpoint


#ifndef __SMART_POINTER_H__
#define __SMART_POINTER_H__

template <class T>
class SmartPointer
{
public:
    typedef T element_type;

    SmartPointer ():_object(NULL), _counter(NULL){}
    SmartPointer(T * object):_object(NULL), _counter(NULL){ Assign(object); }
    SmartPointer(const SmartPointer& sp):_object(NULL), _counter(NULL){ Assign(sp); }
    SmartPointer& operator=(T * object) { Assign(object); return *this; }
    SmartPointer& operator=(const SmartPointer& sp) { Assign(sp); return *this; }
    
    ~SmartPointer() { if (_counter) RemRef(); }
    
    bool operator == (const SmartPointer& sp) { assert(_object != NULL); return ( Get() == sp.Get()); }
    bool operator != (const SmartPointer& sp) { assert(_object != NULL); return ( Get() != sp.Get()); }
    bool operator < (const SmartPointer& sp)  { assert(_object != NULL); return ( Get() > sp.Get()); }
    bool operator()(){ return (_object != NULL); }
    bool operator!() { return (_object == NULL); }
    
    T* operator ->() { assert(_object != NULL); return _object; }
    T& operator * () { assert(_object != NULL); return *_object; }
    const T* operator->() const { assert(_object != NULL); return _object; }
    const T& operator *() const { assert(_object != NULL); return *_object; }
        
    T* Get() const { return _object; }
    int GetCounter() const { return _counter ? *_counter : 0 ?}
    bool Unique() const { return _counter ? (*_counter == 1) : false;}
    
    void Reset(T* object = NULL)
    {
        Assign(object);
    }
    
protected:
    void Assign(T* object)
    {
        if ( _object )
        {
            RemRef();
        }
        
        if ( object )
        {
            try
            {
                _counter = new int;
                AddRef();
            }
            catch ( ... )
            {
                delete object;
                object = NULL;
            }
            
            _object = object;
        }
    }
    
    void Assign(const SmartPointer& sp)
    {
        T* object = sp._object;
        if ( _object != object )
        {
            if ( _counter )
            {
                RemRef();
            }
            _counter = sp._counter;
            _object = sp._object;
            AddRef();
        }
    }
    
    void RemRef()
    {
        assert(_object);
        assert(_counter);
        
        if ( *_counter > 0 && --*_counter == 0 )
        {
            delete _object;
            delete _counter;
        }
        
        _object = NULL;
        _counter = NULL;
    }
    
    void AddRef()
    {
        assert(_counter);
        *_counter++;
    }

private:
    T*      _object;
    int*    _counter;
};



#endif//__SMART_POINTER_H__



阅读更多
文章标签: object null delete class
个人分类: C++
上一篇内存池
下一篇对象池
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭