C++ shared_ptr vs. unique_ptr for resource management

后端 未结 3 924
礼貌的吻别
礼貌的吻别 2021-01-05 16:44

I\'ve been mulling over use of unique_ptr vs shared_ptr vs own_solution. I\'ve discounted the latter as I\'ll almost certainly get it

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 17:37

    So I suppose what I'm looking for is a deferencable weak_ptr that cannot be converted into a shared_ptr.

    You could hand out your one little helper class:

    template
    class NonConvertibleWeakPtr
    {
    public:
       NonConvertibleWeakPtr(const std::shared_ptr& p) : p_(p) {}
       ... // other constructors / assignment operators
       bool expired() const { return p_.expired(); }
       T* operator->() const { return get(); }
       T& operator*() const { return *get(); }
    private:
       T* get() const { return p_.lock().get(); }
    private:
       std::weak_ptr p_;
    };
    

    This is slightly better than a raw pointer, because you can check if your pointer is still valid.

    Example usage:

    std::shared_ptr sp = std::make_shared(5);
    {
        NonConvertibleWeakPtr wp(sp);
        if(!wp.expired()) {
            std::cout << *wp << std::endl;
        }
    }
    

    However a user can still misuse it for example with std::shared_ptr blah(&(*wp));, but it takes a bit more criminal energy.

提交回复
热议问题