shared_from_this() 實現原理


shared_from_this() 實現原理

shared_ptr 實現原理

作用

  • C++中采用new和delete來申請和釋放內存,但如果管理不當,很容易出現內存泄漏
  • std::shared_ptr, std::unique_ptr, std::weak_ptr,三種智能指針類,可以自動管理內存

使用示例

  • 智能指針對象,和一般的指針用法幾乎完全相同
#include <iostream>
#include  <memory> // 需要包含這個頭文件

int main()
{
	std::shared_ptr<int> p1 = std::make_shared<int>();
	*p1 = 78;
	std::cout << "p1 = " << *p1 << std::endl; // 輸出78
	return 0;
}

原理

  • 智能指針類包含兩個成員變量:引用計數指針,管理對象的指針

  • 當引用計數為0時,釋放內存,否則不處理

  • 重載和使用相關的所有操作符等,比如賦值運算符會將引用計數+1

  • 重載*操作符,可獲得管理對象的指針

  • 可參考實現的demo

    #include<bits/stdc++.h>
    using namespace std;
    
    template <typename MyStruct>
    class SharedPtr {
    public:
        SharedPtr(MyStruct* a) 
        : a_(a) {
            cout << "SharedPtr()" << endl;
            b_ = new atomic<int>(1);
        }
        ~SharedPtr() {
            cout << "~SharedPtr()" << endl;
            if (!(--*b_)) {
                cout << "delete real ptr" << endl;
                ToStirng();
                delete a_;
                a_ = NULL;
                delete b_;
                b_ = NULL;
            }
        }
        SharedPtr<MyStruct>& operator =(const SharedPtr<MyStruct>& another) {
            cout << "operator =" << endl;
            if (this != &another) {
               if (this->a_) {
                    if (!(--*this->b_)) {
                        cout << "delete real ptr" << endl;
                        ToStirng();
                        delete this->a_;
                        this->a_ = NULL;
                        delete this->b_;
                        this->b_ = NULL;
                    }
               }
               if (another.a_) {
                     this->a_ = another.a_;
                     this->b_ = another.b_;
                     *this->b_ ++ ;
               }
            }
            return *this;
        }
    
    MyStruct operator *() {
        cout << "operator *" << endl;
        return *a_;
    }
    
    private:
        void ToStirng() {
            cout << *a_ << endl;
        }
        MyStruct* a_;
        atomic<int>* b_;  
    };
    
    int main() {
        string* my_struct = new string("str1");
        SharedPtr<string> a(my_struct);
        string* my_struct2 = new string("str2");
        SharedPtr<string> b(my_struct2);
        b = a;
        cout << *b << endl;
        return 0;
    }
    

shared_from_this() 實現原理

使用場景

  • 當類被share_ptr管理
  • 調用類的成員函數時
  • 需要把當前對象指針作為參數傳給其他函數時
  • 需要傳遞一個指向自身的share_ptr

使用前提

  • 繼承enable_shared_from_this

使用示例

struct EnableSharedPtr : enable_shared_from_this<EnableSharedPtr> {
public:
    shared_ptr<EnableSharedPtr> getptr() {
        return shared_from_this();
    }
    ~EnableSharedPtr() { 
        cout << "~EnableSharedPtr() called" << endl; 
    }
};

int main()
{
    shared_ptr<EnableSharedPtr> gp1(new EnableSharedPtr());
    // 注意不能使用raw 指針
    // EnableSharedPtr* gp1 = new EnableSharedPtr();
    shared_ptr<EnableSharedPtr> gp2 = gp1->getptr();
    cout << "gp1.use_count() = " << gp1.use_count() << endl;
    cout << "gp2.use_count() = " << gp2.use_count() << endl;
    return 0;
}

原理

  • boost精簡代碼如下

    class enable_shared_from_this
    {
        shared_ptr<const _Tp> shared_from_this() const
        {
            return shared_ptr<const _Tp>(this->_M_weak_this);
        }
    
        mutable weak_ptr<_Tp> _M_weak_this;
    };
    
  • 可理解為enable_shared_from_this 包含引用計數指針

  • 所有與該對象相關的操作都與該引用計數指針相關

  • 因為類內部,如果不包含引用計數指針,不能直接生成shared_ptr

  • 只有智能指針管理的對象,才能使用shared_from_this,因為普通對象不包含引用計數指針
  • 構造函數內不能使用shared_from_this(),因為智能指針在構造函數后生成,構造函數時還不存在引用計數指針


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM