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方式继承。

相关文章
相关标签/搜索