主要的思路是使用一个int* 的指针进行计数,在构造函数时候设置为0,并加1(或者直接设置为1)。然后赋值和复制构造时候把int* 和数据保存的指针T* mP传到另外一个类中。在赋值的时候要注意左边的指针是否已经有数据了,有数据就要先-1,然后再进行赋值。
template<typename T>
class ref1
{
public:
explicit ref1(T* p = NULL) : mP(p), sCount(new int)
{
*sCount = 0;
++(*sCount);
std::cout << "constructor" << std::endl;
std::cout << *sCount << std::endl;
}
ref1(const ref1& copy)
{
if (this != ©)
{
this->mP = copy.mP;
this->sCount = copy.sCount;
++(*sCount);
std::cout << "copy " << std::endl;
std::cout << *sCount << std::endl;
}
}
ref1& operator=(const ref1& rhs)
{
if (mP == rhs.mP)
{
return *this;
}
std::cout << "= construct2 " << std::endl;
std::cout << *sCount << std::endl;
//原来已经有一个对象了
if (sCount > 0)
{
std::cout << *sCount << std::endl;
--(*sCount);
std::cout << *sCount << std::endl;
if (*sCount == 0)
{
std::cout << "delete other" << std::endl;
if (mP != nullptr)
{
delete mP;
mP = nullptr;
}
if (sCount != nullptr)
{
delete sCount;
sCount = nullptr;
}
}
}
this->mP = rhs.mP;
this->sCount = rhs.sCount;
++(*sCount);
std::cout << "= construct " << std::endl;
std::cout << *sCount << std::endl;
return *this;
}
~ref1()
{
--(*sCount);
std::cout << "deconstruct " << std::endl;
std::cout << *sCount << std::endl;
if (*sCount == 0)
{
std::cout << "delete" << std::endl;
if (mP != nullptr)
{
delete mP;
mP = nullptr;
}
if (sCount != nullptr)
{
delete sCount;
sCount = nullptr;
}
}
}
protected:
int *sCount;
T* mP;
};
template<typename T>
class ref1
{
public:
explicit ref1(T* p = NULL) : mP(p), sCount(new int)
{
*sCount = 0;
++(*sCount);
std::cout << "constructor" << std::endl;
std::cout << *sCount << std::endl;
}
ref1(const ref1& copy)
{
if (this != ©)
{
this->mP = copy.mP;
this->sCount = copy.sCount;
++(*sCount);
std::cout << "copy " << std::endl;
std::cout << *sCount << std::endl;
}
}
ref1& operator=(const ref1& rhs)
{
if (mP == rhs.mP)
{
return *this;
}
std::cout << "= construct2 " << std::endl;
std::cout << *sCount << std::endl;
//原来已经有一个对象了
if (sCount > 0)
{
std::cout << *sCount << std::endl;
--(*sCount);
std::cout << *sCount << std::endl;
if (*sCount == 0)
{
std::cout << "delete other" << std::endl;
if (mP != nullptr)
{
delete mP;
mP = nullptr;
}
if (sCount != nullptr)
{
delete sCount;
sCount = nullptr;
}
}
}
this->mP = rhs.mP;
this->sCount = rhs.sCount;
++(*sCount);
std::cout << "= construct " << std::endl;
std::cout << *sCount << std::endl;
return *this;
}
~ref1()
{
--(*sCount);
std::cout << "deconstruct " << std::endl;
std::cout << *sCount << std::endl;
if (*sCount == 0)
{
std::cout << "delete" << std::endl;
if (mP != nullptr)
{
delete mP;
mP = nullptr;
}
if (sCount != nullptr)
{
delete sCount;
sCount = nullptr;
}
}
}
protected:
int *sCount;
T* mP;
};