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");
    }
    
  • 相关阅读:
    Microsoft NNI入门
    【神经网络搜索】Efficient Neural Architecture Search
    Sphinx 快速构建工程文档
    Ubuntu16.04 Cuda11.1 Cudnn8.1 Tensorflow2.4 PyTorch1.7环境配置
    【CV中的Attention机制】ShuffleAttention
    【有趣的NAS】NAS-RL(ICLR2017)
    分类器
    将url下载到本地
    缓存管理器
    大数据数据结构-分类模型
  • 原文地址:https://www.cnblogs.com/wnwin/p/11503693.html
Copyright © 2011-2022 走看看