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; }
相关文章推荐
- Using C++ std::equal on a container of shared_ptr
- c++中关于智能指针std::tr1::shared_ptr的用法
- vs2008 error C2039: “shared_ptr”: 不是“std::tr1”的成员
- std::tr1::shared_ptr 使用的一点体会
- 智能指针 boost(scoped_ptr,scoped_array,shared_ptr,shared_array) 和 std (auto_ptr)的比较 .
- error: ‘shared_ptr’ in namespace ‘std’ does not name a type
- std::shared_ptr
- 【STL学习】智能指针之shared_ptr
- C++11 shared_ptr, weak_ptr速成,以及放在stl集合类里面的注意点。
- STL概览-通用工具pair,auto_ptr,std::rel_ops(二)
- 关于std:auto_ptr std:shared_ptr std:unique_ptr
- tolua 转换 std::shared_ptr
- Effective Modern C++ 条款20 把std::weak_ptr当作类似std::shared_ptr的、可空悬的指针使用
- 智能指针(一):STL auto_ptr实现原理
- C++11智能指针之std::shared_ptr
- [C++] Boost智能指针——boost::shared_ptr(使用及原理分析)
- [置顶] STL中的智能指针(Smart Pointer)及其源码剖析: std::auto_ptr
- c++11 条款19:使用std::shared_ptr来进行共享所有权的资源管理
- 智能指针 std::auto_ptr 和 shared_ptr
- Effective C++: 探智能指针(std::shared_ptr)和左值引用.