不说了,直接贴代码。。
#ifndef PASS_REF_PTR
#define PASS_REF_PTR
#include "SharedPtr.h"
namespace moora_utils
{
template <class _Ty>
class SharedPtr;
template <class _Ty>
class PassRefPtr
{
_Ty* ptr_;
public:
//use it carefully
_Ty* get(){return ptr_;}
explicit PassRefPtr(_Ty* ptr):ptr_(ptr)
{
}
template <class _Tu>
PassRefPtr(const PassRefPtr<_Tu>& other):ptr_(other.get())
{
}
template <class _Tu>
PassRefPtr(SharedPtr<_Tu>& other);
template <class _Tu>
PassRefPtr& operator=(PassRefPtr<_Tu>& other)
{
this->ptr_ = other.ptr_;
return *this;
}
_Ty* operator->()
{
return ptr_;
}
template <class _Tu>
PassRefPtr& operator=(SharedPtr<_Tu>& other);
};
template <class _Ty> template <class _Tu> inline
PassRefPtr<_Ty>::PassRefPtr(SharedPtr<_Tu>& other):ptr_(other.get()){}
template <class _Ty> template <class _Tu> inline
PassRefPtr<_Ty>& PassRefPtr<_Ty>::operator=(SharedPtr<_Tu>& other)
{
ptr_ = other.get();
}
}
#endif
#ifndef SHARED_PTR
#define SHARED_PTR
#include "PassRefPtr.h"
namespace moora_utils {
template <class _Ty>
class PassRefPtr;
template <class _Ty>
class SharedPtr
{
_Ty* ptr_;
public:
//use it carefully
_Ty* get()
{
return ptr_;
}
explicit SharedPtr(_Ty* ptr):ptr_(ptr)
{
ptr_->ref();
}
template <class _Tu>
SharedPtr(const SharedPtr<_Tu>& other):ptr_(other.get())
{
ptr_->ref();
}
template <class _Tu>
SharedPtr(PassRefPtr<_Tu>& other);
template <class _Tu>
SharedPtr& operator=(SharedPtr<_Tu>& other)
{
ptr_->deref();
ptr_ = other.get();
ptr_->ref();
return *this;
}
template <class _Tu>
SharedPtr& operator=(PassRefPtr<_Tu>& other);
_Ty* operator->()
{
return ptr_;
}
~SharedPtr()
{
if (!ptr_->deref())
{
delete ptr_;
ptr_ = NULL;
}
}
};
template <class _Ty> template <class _Tu> inline
SharedPtr<_Ty>& SharedPtr<_Ty>::operator=(PassRefPtr<_Tu>& other)
{
ptr_ = other.get();
ptr_->ref();
return *this;
}
template <class _Ty> template <class _Tu> inline
SharedPtr<_Ty>::SharedPtr(PassRefPtr<_Tu>& other):ptr_(other.get())
{
ptr_->ref();
}
}
#endif
posted on 2011-08-18 01:00
Hinter 阅读(171)
评论(0) 编辑 收藏 引用