泛型句柄类之写时复制疑问

匚匚 匚匚 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
如何让泛型句柄类做到写时自动去复制对象呢?
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;
}
}
...全文
评论 3
收藏 已收藏
分享
返回顶部
匚匚
C++ 语言 65,214 成员 250,514 内容