64,636
社区成员
发帖
与我相关
我的任务
分享
#ifndef __SCCP_SCOPEDPTR_H__
#define __SCCP_SCOPEDPTR_H__
namespace scpp
{
template <typename T>
class RefCountPtr
{
public:
explicit RefCountPtr(T* p = NULL)
{
Create(p);
}
RefCountPtr(const RefCountPtr<T>& rhs)
{
Copy(rhs);
}
RefCountPtr<T>& operator = (const RefCountPtr<T>& rhs)
{
if (ptr_ != rhs.ptr_)
{
Kill();
Copy(rhs);
}
return *this;
}
RefCountPtr<T>& operator = (T *p)
{
if (ptr_ != p)
{
Kill();
Create(p);
}
return *this;
}
~RefCountPtr()
{
std::cout << "kill" << std::endl;
Kill();
}
public:
T* Get() const { return ptr_; }
T* operator ->() const
{
std::cout << "in this" << std::endl;
return ptr_;
}
T& operator *() const
{
return *ptr_;
}
private:
void Create(T* p)
{
ptr_ = p;
if (ptr_ != NULL)
{
refCount_ = new int;
*refCount_ = 1;
}
else
{
refCount_ = NULL;
}
}
void Copy(const RefCountPtr<T>& rhs)
{
ptr_ = rhs.ptr_;
refCount_ = rhs.refCount_;
if (refCount_ != NULL)
{
++(*refCount_);
}
}
void Kill()
{
if (refCount_ != NULL)
{
if (--(*refCount_) == 0)
{
delete ptr_;
ptr_ = NULL;
delete refCount_;
refCount_ = NULL;
}
}
}
private:
T* ptr_;
int* refCount_;
};
} // namespace scpp
#endif // __SCCP_SCOPEDPTR_H__
// debug.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
#include "scpp_refcountptr.h"
class Student
{
public:
Student(int age) : age_(age)
{
}
void ShowAge()
{
std::cout << "my age is : " << age_ << std::endl;
}
private:
int age_;
};
int _tmain(int argc, _TCHAR* argv[])
{
scpp::RefCountPtr<Student> smartPoint(new Student(10));
scpp::RefCountPtr<Student> smartPoint2;
smartPoint2 = smartPoint; //@test:赋值操作符
smartPoint = NULL;
smartPoint2->ShowAge();
scpp::RefCountPtr<Student> smartPoint3(smartPoint2); //@test:拷贝构造函数
smartPoint2 = NULL;
smartPoint3->ShowAge();
scpp::RefCountPtr<Student> *smartPoint4; //@test:引用
smartPoint4 = &smartPoint3;
smartPoint4->Get()->ShowAge();
Student studen3 = *smartPoint3; //@test:Get()
studen3.ShowAge();
smartPoint3 = NULL;
return 0;
}
scpp::RefCountPtr<Student>(new Student [10]); // undefined behavior in Kill, at best memory leak.