64,639
社区成员
发帖
与我相关
我的任务
分享
template<class T> class Handle
{
T *ptr;
int *use;
public:
Handle(const T t):ptr(new T(t)),use(new int(0)){}
Handle(const Handle &);
Handle& operator=(const Handle& );
T& operator*() ;
T* operator&() ;
~Handle();
};
template<class T> Handle<T>::Handle(const Handle &rhs)
{
ptr=rhs.ptr;
*use++;
}
template<class T> Handle<T>& Handle<T>::operator=(const Handle &rhs)
{
*rhs.use++;
if(!*use)
{
delete ptr;
}
ptr=rhs.ptr;
*use--;
use=rhs.use;
return *this;
}
template<class T> T& Handle<T>::operator*()
{
if(ptr)
return *ptr;
}
template<class T> T* Handle<T>::operator&()
{
if(ptr)
return ptr;
}
template<class T> Handle<T>::~Handle()
{
if(--*use)
{delete ptr;delete use;}
}
int main()
{
Handle<string> h(string("abcdef"));
cout<<(*h).c_str()<<endl;
system("pause");
return 0;
}