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

匚匚 2011-10-22 02:17:32
如何让泛型句柄类做到写时自动去复制对象呢?
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;
}
}
...全文
78 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
匚匚 2011-10-22
  • 打赏
  • 举报
回复

template <class T> inline T& Handle<T>::operator*()
{
if (ptr) {copy();return *ptr;} ///
throw std::runtime_error("dereference of unbound Handle");
}

Handle<int> a(new int(8));
Handle<int> b(a);
cout<<*a<<" "<<*b<<endl;//连输出也要复制,无语
匚匚 2011-10-22
  • 打赏
  • 举报
回复
呵呵
呵呵
呵呵
匚匚 2011-10-22
  • 打赏
  • 举报
回复
template <class T> inline
Handle<T>& Handle<T>::copy() //写时复制???
{
if(!isOnly()) // 1 == *use
{
--*use;
ptr=new T(*ptr);
use=new std::size_t(1);
}
return *this;
}

64,639

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧