泛型句柄类之写时复制疑问
如何让泛型句柄类做到写时自动去复制对象呢?
Handle<int> a(new int(8));
Handle<int> b(a);
*b=9; //要改变b所指对象的值且计数器不为1,此时句柄应自动复制对象并与原对象断开
cout<<*a<<" "<<*b<<endl;
而下面的句柄模板,重载的*或->返回的是 *ptr 或 ptr ,并没有做到写时复制吧?
Handle<int> a(new int(8));
Handle<int> b(a);
*b=9; //要改变b所指对象的值且计数器不为1,此时句柄应自动复制对象并与原对象断开
cout<<*a<<" "<<*b<<endl;
而下面的句柄模板,重载的*或->返回的是 *ptr 或 ptr ,并没有做到写时复制吧?
template <class T>
class Handle
{
public:
Handle(T *p = 0): ptr(p), use(new std::size_t(1)){}
Handle(const Handle& h): ptr(h.ptr), use(h.use){ ++*use; }
Handle& operator=(const Handle&);
~Handle() { rem_ref(); }
T& operator*();
T* operator->();
const T& operator*() const;
const T* operator->() const;
private:
T* ptr;
std::size_t *use;
void rem_ref();
};
template <class T>
inline Handle<T>& Handle<T>::operator=(const Handle &rhs)
{
++*rhs.use;
rem_ref();
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");
}
template <class T> inline
void Handle<T>::rem_ref()
{
if (--*use == 0)
{
delete ptr; delete use;
}
}
...全文
相关推荐
C++典型句柄类的实现
演示了继承中的易错点,演示了两种常用C++句柄类的封装方式,前者适用于类的基类指针管理以便实现多态,后者不仅管理基类指针还管理子类对象的创建。
详解C++句柄类
本篇文章给大家详细分析了C++句柄类的相关知识点,对此有需要的朋友跟着学习参考下吧。
Java中泛型的各种使用
NULL 博文链接:https://dyygusi.iteye.com/blog/1988932
C++实现句柄类
用C++实现的句柄类,有利于初学者理解什么是句柄~~
C#泛型概念的简介与泛型的使用
今天小编就为大家分享一篇关于C#泛型概念的简介与泛型的使用,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧


