💗 💗 博客:小怡同學
💗 💗 個人簡介:編程小萌新
💗 💗 如果博客對大家有用的話,請點贊關注再收藏 🌞
智能指針的使用及原理
AII(Resource Acquisition Is Initialization)是一種利用對象生命周期來控制程序資源(如內
存、文件句柄、網絡連接、互斥量等等)的簡單技術。
在對象構造時獲取資源,接著控制對資源的訪問使之在對象的生命周期內始終保持有效,最后在對象析構的時候釋放資源。
std::auto_ptr
c++98版本的庫中就提供了auto_ptr的智能指針。下面演示的auto_ptr的使用及問題。
auto_ptr的實現原理:管理權轉移的思想,下面簡化模擬實現了一份bit::auto_ptr、
template<class T>class auto_ptr{public:auto_ptr(T* ptr):_ptr(ptr){}auto_ptr(const auto_ptr<T>& ap){_ptr = ap._ptr;ap._ptr = nullptr;}auto_ptr<T>& operator=(const auto_ptr<T>& ap){if (&ap == this)return *this;_ptr = ap._ptr;ap._ptr = nullptr;}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}~auto_ptr(){delete _ptr;}private:T* _ptr;};
std::unique_ptr
unique_ptr的實現原理:簡單粗暴的防拷貝,下面簡化模擬實現了一份UniquePtr來
template<class T>class unique_ptr{public:unique_ptr(T* ptr):_ptr(ptr){}unique_ptr(const unique_ptr<T>& ap) = delete;//防止拷貝unique_ptr<T>& operator=(const unique_ptr<T>& ap) = delete;T& operator*(){return *_ptr;}T* operator->(){return _ptr;}~unique_ptr(){delete _ptr;}private:T* _ptr;};
std::shared_ptr
c++11中開始提供更靠譜的并且支持拷貝的shared_ptr
template<class T>class shared_ptr{public://這個函數是模擬仿函數傳進來的場景主要作用顯示釋放內存,其他成員函數調用不了D類型所以在成員變量中加入包裝類函數這樣類中都能使用這個函數了template<class D>shared_ptr(T* ptr, D del):_ptr(ptr), count(new int(1)), _del(del){}shared_ptr(T* ptr):_ptr(ptr), count(new int(1)){}shared_ptr(const shared_ptr<T>& sp){_ptr = sp._ptr;count = sp.count;++(*count);}shared_ptr<T>& operator=(const shared_ptr<T>& sp){if (this == &sp)return this;_ptr = sp._ptr;count = sp.count;++(*count++);}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}~shared_ptr(){if (--(*count) == 0){_del(_ptr);delete count;}}private:T* _ptr;int* count;function<void(T*)> _del = [](T* ptr) {delete ptr; };};
}
shared_ptr會出現循環引用的現象他的解決方案:在引用計數的場景下,節點中的_prev和_next改成weak_ptr就可以了
template<class T>class weak_ptr{weak_ptr():_ptr(nullptr){}weak_ptr(const shared_ptr<T>& sp):_ptr(sp._ptr){}weak_ptr<T>& operator=(const shared_ptr<T>& sp):_ptr(sp._ptr){return* this;}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}private:T* _ptr;};