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

前端 未结 5 776
醉话见心
醉话见心 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 03:00

    This ground has already been covered by Herb Sutter in GotW #91 - Smart Pointer Parameters. It touches on the performance aspect as well, whilst the other answers, while great, focus on memory management.

    Someone above recommended passing a smart pointer as const reference - changed his mind in later edit. We had code where this was abused - it made the signatures 'smarter' - i.e. more complicated but no benefit. The worst is when a junior developer takes over - he would not question as @Michael and 'learn' how to do it from a bad example. It works, but...

    To me the smart pointer parameter passing matter is serious enough to be mentioned prominently in any book/article/post immediately after explaining what smart pointers are.

    Wondering now if lint-like programs should flag passing by const reference as element of style.

提交回复
热议问题