zoukankan      html  css  js  c++  java
  • 语言基础(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");
    }
    
  • 相关阅读:
    elasticsearch
    超人学院课课程体系
    51cto大数据培训路线
    关于举办大数据处理技术培训的通知
    “大数据分析高级工程师”培训
    成都大数据Hadoop与Spark技术培训班
    大数据时代新闻采编人员职业能力培训
    EXCEL常用函数
    大数据实时处理-基于Spark的大数据实时处理及应用技术培训
    Properties vs. Attributes
  • 原文地址:https://www.cnblogs.com/wnwin/p/11503693.html
Copyright © 2011-2022 走看看