Getting a boost::shared_ptr for this

前端 未结 6 2062
有刺的猬
有刺的猬 2020-12-02 07:11

I am making extensive use of boost:shared_ptr in my code. In fact, most of the objects that are allocated on the heap are held by a shared_ptr. Unf

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 07:52

    With C++11 shared_ptr and enable_shared_from_this is now in the standard library. The latter is, as the name suggests, for this case exactly.

    http://en.cppreference.com/w/cpp/memory/shared_ptr

    http://en.cppreference.com/w/cpp/memory/enable_shared_from_this

    Example bases on that in the links above:

    struct Good: std::enable_shared_from_this{
        std::shared_ptr getptr() {
            return shared_from_this();
        }
    };
    

    use:

    std::shared_ptr gp1(new Good);
    std::shared_ptr gp2 = gp1->getptr();
    std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';
    

提交回复
热议问题