关闭

对象池

294人阅读 评论(0) 收藏 举报


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__



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:29001次
    • 积分:584
    • 等级:
    • 排名:千里之外
    • 原创:29篇
    • 转载:5篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论