您的位置:首页 > 其它

STL:std::shared_ptr大致原理.

2017-03-02 00:00 393 查看
摘要: 仅仅对智能指针的原理有一个大概的了解

#include <iostream>
#include <type_traits>

template<typename Ty>
class SharedPtr {
public:
SharedPtr() = default;

//显式的接受数据创建一个智能指针.
explicit SharedPtr(Ty&& value);
explicit SharedPtr(const Ty& value);

~SharedPtr();

SharedPtr(const SharedPtr<Ty>& other);
SharedPtr(SharedPtr<Ty>&& other);

//notice that:
//当对 SharedPtr进行 *(解引用操作)的时候会调用这个先把SharedPtr转为指针.
operator Ty*()noexcept;

SharedPtr<Ty>& operator=(const SharedPtr<Ty>& other);
SharedPtr<Ty>& operator=(SharedPtr<Ty>&& other);

private:
mutable int counter{ 0 }; //引用计数.
Ty* data{ nullptr }; //存储数据的指针.
};

template<typename Ty>
SharedPtr<Ty>::SharedPtr(Ty&& value)
:data{ new Ty{std::move(value)} },
counter{0}
{
++(this->counter);
}

template<typename Ty>
SharedPtr<Ty>::SharedPtr(const Ty& value)
: data{ new Ty{value} },
counter{ 0 }
{
++(this->counter);
}

template<typename Ty>
SharedPtr<Ty>::SharedPtr(const SharedPtr<Ty>& other)
:counter{ other.counter },
data{ other.data }
{
++(this->counter);
++(other.counter);
}

template<typename Ty>
SharedPtr<Ty>::SharedPtr(SharedPtr<Ty>&& other)
:counter{ std::move(other.counter) },
data{ std::move(other.data) }
{
other.counter = 0;
other.data = nullptr;
}

template<typename Ty>
SharedPtr<Ty>& SharedPtr<Ty>::operator=(const SharedPtr<Ty>& other)
{
if ((this->counter - 1) == 0) {
delete (this->data);
this->data = nullptr;
}

++(other.counter);
this->counter = other.counter;
this->data = other.data;

return *this;
}

template<typename Ty>
SharedPtr<Ty>& SharedPtr<Ty>::operator=(SharedPtr<Ty>&& other)
{
this->counter = std::move(other.counter);
this->data = std::move(other.data);

other.counter = 0;
other.data = nullptr;

return *this;
}

template<typename Ty>
SharedPtr<Ty>::operator Ty*()noexcept
{
std::cout << "change to ptr" << std::endl;
return (this->data);
}

template<typename Ty>
SharedPtr<Ty>::~SharedPtr()
{
--(this->counter);
if (this->counter == 0) {
delete (this->data);
this->data = nullptr;
}
}

int main()
{
SharedPtr<int> ptr{ 20 };
std::cout << *ptr << std::endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: