64,644
社区成员
发帖
与我相关
我的任务
分享
template<typename T>
class _shared_ptr
{
public:
_shared_ptr(T *ptr) : _ptr(ptr), _cnt(new long(1)){}
template<typename U>
_shared_ptr(_shared_ptr<U> &other)
{
_ptr = reinterpret_cast<T*>(other.operator->());
_cnt = other.get_cnt();
++*_cnt;
}
template<typename U>
_shared_ptr<T>& operator=(const _shared_ptr<U> &rhs)
{
if (this != &other)
{
if (!--*_cnt)
{
delete _ptr;
delete _cnt;
}
_ptr = reinterpret_cast<T*>(other.operator->());
_cnt = other.get_cnt();
++*_cnt;
}
return *this;
}
~_shared_ptr()
{
if (!--*_cnt)
{
delete _ptr;
delete _cnt;
}
}
T* operator->() const
{
assert(_ptr);
return _ptr;
}
T& operator*() const
{
assert(_ptr);
return *_ptr;
}
long* get_cnt() const
{
return _cnt;
}
private:
T *_ptr;
long *_cnt;
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<_shared_ptr<int> > vec;
_shared_ptr<int> p1(new int(1));
_shared_ptr<int> p2(new int(2));
vec.push_back(p1);
vec.push_back(p2);
ofstream os("g:\\ptr.txt");
os << vec[0].operator->() << ' ' << *vec[0] << endl;
os << vec[1].operator->() << ' ' << *vec[1] << endl;
return 0;
}