shared_from_this 用法

                                                                                                                                                                                             

#include <iostream>ios

#include <memory>函數


class A:public std::enable_shared_from_this<A>{this

    public:spa

    A(){繼承

    }   get

    ~A(){io


    }   class

    std::shared_ptr<A> getsp(){stream

        return shared_from_this();構造函數

    }   

};


int main(int argc, char* argv[]){

    //std::shared_ptr<A> a = std::make_shared<A>();

    std::shared_ptr<A> a(new A());

    std::cout<<"a.use_count() = "<<a.use_count()<<std::endl;

    std::shared_ptr<A> b = a->getsp();

    std::cout<<"b.use_count() = "<<b.use_count()<<std::endl;

    return 0;

}


//用 stl 的 enable_shared_from_this,須要顯式定義類無參默認構造函數和析構函數,必須從使用std::shared_ptr<>實例來調用getst(); std::enable_shared_from_this 需用public方式繼承。

相關文章
相關標籤/搜索