语言基础(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");
}
posted @ 2019-05-10 23:02  ningKing  阅读(281)  评论(0编辑  收藏  举报