Should I use std::shared pointer to pass a pointer?

前端 未结 5 770
醉话见心
醉话见心 2021-02-04 02:18

Suppose I have an object which is managed by an std::unique_ptr. Other parts of my code need to access this object. What is the right solution to pass the pointer?

5条回答
  •  情话喂你
    2021-02-04 02:41

    Typically you would just pass a reference or plain pointer to other parts of the code that wish to observe the object.

    Pass by reference:

    void func(const Foo& foo);
    
    std::unique_ptr ptr;
    
    // allocate ptr...
    
    if(ptr)
        func(*ptr);
    

    Pass by raw pointer:

    void func(const Foo* foo);
    
    std::unique_ptr ptr;
    
    // allocate ptr...
    
    func(ptr.get());
    

    The choice will depend on the need to pass a null pointer.

    It is your responsibility to ensure by-design that observers do not use the pointer or reference after the unique_ptr has been destroyed. If you can't guarantee that then you must use a shared_ptr instead of a unique_ptr. Observers can hold a weak_ptr to indicate that they do not have ownership.

    EDIT: Even if observers wish to hold on to the pointer or reference that is OK but it does make it more difficult to ensure it will not be used after the unique_ptr has been destroyed.

提交回复
热议问题