Non-ownership copies of std::unique_ptr

前端 未结 1 593
后悔当初
后悔当初 2021-01-26 21:02

There\'s two containers: owner and non-owner of resource. As I have only 1 owner, I suppose I need unique_ptr.

class OwnershipContainer {
public:
    void add(st         


        
相关标签:
1条回答
  • 2021-01-26 21:12

    You actually do have shared ownership: When you access the object via the NonOwningContainer-contained pointer-like thing, you must take ownership, or the object may disappear out from under you while you're working with it.

    Since you can't guarantee the object won't disappear out from under you:

    But i cannot give guarantee that lifetime of Obj match or exceed lifetime of Non-owner container.

    then your only option is to share ownership. Hence shared_ptr and weak_ptr is the appropriate approach.

    Also, depending on the difference in lifetime of OwnershipContainer and NonOwnershipContainer, be aware of the interaction between std::make_shared and std::weak_ptr.

    0 讨论(0)
提交回复
热议问题