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

前端 未结 5 772
醉话见心
醉话见心 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:54

    Don't focus so much on the caller's requirements. What does the function need to be passed in? If it's only going to use the object for the duration of the call, then use a reference.

    void func(const Foo& foo);
    

    If it needs to retain ownership of the object past its duration, then pass in a shared_ptr

    void func(std::shared_ptr foo);
    

提交回复
热议问题