• 语言基础(24):句柄类


    1、句柄类可以做到两点好处:

    ▪ 减少编译量,修改底层类,不需要编译句柄类;
    ▪ 隔离信息,隐藏了底层细节,用户只能够看到,类开放出来的接口;
    

    2、实现一个泛型句柄类:

    template <class T> class Handle {
    public:
    	// unbound handle
    	Handle(T *p = 0): ptr(p), use(new size_t(1)) { }
    	// overloaded operators to support pointer behavior
    	T& operator*();
    	T* operator->();
    	const T& operator*() const;
    	const T* operator->() const;
    	// copy control: normal pointer behavior, but last Handle deletes the object
    	Handle(const Handle& h): ptr(h.ptr), use(h.use) { ++*use; }
    	Handle& operator=(const Handle&);
    	~Handle() { rm_ref(); }
    	
    private:
    	T* ptr;      // shared object
    	size_t *use; // count of how many Handle point to *ptr
    	
    	void rm_ref() { if (--*use == 0) { delete ptr; delete use; } }
    };
    
    template <class T>
    inline Handle<T>& Handle<T>::operator=(const Handle &rhs)
    {
    	++*rhs.use; // protect against self-assignment
    	rm_ref();   // decrement use count and delete pointers if needed
    	ptr = rhs.ptr;
    	use = rhs.use;
    	return *this;
    }
    
    template <class T> inline T& Handle<T>::operator*()
    {
    	if (ptr) return *ptr;
    	throw std::runtime_error
    		("dereference of unbound Handle");
    }
    
    template <class T> inline T* Handle<T>::operator->()
    {
    	if (ptr) return ptr;
    	throw std::runtime_error
    		("access through unbound Handle");
    }
    
    template <class T> inline const T& Handle<T>::operator*() const
    {
    	if (ptr) return *ptr;
    	throw std::runtime_error
    		("dereference of unbound Handle");
    }
    
    template <class T> inline const T* Handle<T>::operator->() const
    {
    	if (ptr) return ptr;
    	throw std::runtime_error
    		("access through unbound Handle");
    }
    
  • 相关阅读:
    easyui 获取分页栏中的行数(pageSize)和页码数(pageNumber)
    C# 跨盘符移动文件
    C# Json简单处理
    HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth之完全详解
    Jquery中的(function($){...})(jQuery)
    前端框架你究竟选什么
    Kindeditor使用心得
    jvm——内存模型
    jvm——NIO
    Java——静态类型 实际类型
  • 原文地址:https://www.cnblogs.com/wnwin/p/11503693.html
Copyright © 2020-2023  润新知