智能指针的简单实现
Posted zuofaqi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了智能指针的简单实现相关的知识,希望对你有一定的参考价值。
template <class T>
class Sp
public:
Sp(T* ptr = nullptr) : ptr_(ptr), count_(new size_t)
if (ptr)
*count_ = 1;
else
*count_ = 0;
Sp(const Sp& other)
ptr_ = other.ptr_;
count_ = other.count_;
(*count_)++;
Sp& operator=(const Sp& src)
if (ptr_ == src.ptr_)
return *this;
ReleaseCount();
ptr_ = src.ptr_;
count_ = src.count_;
(*count_)++;
return *this;
size_t use_count()
return *count_;
T& operator*()
if (ptr_)
return *ptr_;
T* operator->()
if (ptr_)
return ptr_;
operator bool() const
return ptr_ != nullptr;
~Sp()
ReleaseCount();
private:
void ReleaseCount()
if (ptr_)
(*count_)--;
if (*count_ == 0)
delete ptr_;
delete count_;
T* ptr_ nullptr;
size_t* count_ nullptr;
;
class Base
public:
Base()
printf("con\n");
~Base()
printf("decon\n");
;
以上是关于智能指针的简单实现的主要内容,如果未能解决你的问题,请参考以下文章