函数调用共享指针,其对象应为const

use*_*005 3 c++ smart-pointers shared-ptr

我有一个a类型的变量A.

A a;
Run Code Online (Sandbox Code Playgroud)

我想调用一个函数,它将类型的const引用A作为输入参数.

fun(const A &a);
Run Code Online (Sandbox Code Playgroud)

在一些代码更改后,我决定最好将变量类型更改astd::shared_ptr<A>

std::shared_ptr<A> a;
Run Code Online (Sandbox Code Playgroud)

更改函数的最佳方法是什么fun,以确保对象a永远不会更改(它应该保持const)?

fun保持原样,我应该称之为:

fun(*a.get())
Run Code Online (Sandbox Code Playgroud)

还是有其他选择吗?不知怎的,这对我来说很难看......

我猜简单地改变funfun(const std::shared_ptr<A> &a)无法工作,因为我想确保该功能不会改变基本的对象,而不是共享的指针.

我不能使用,std::shared_ptr<const A> a因为有必要a在某个时候改变变量.

lub*_*bgr 5

由于void fun(const A& a);似乎没有对参数的生命周期产生任何影响,请保留现在的签名(传递std::shared_ptrstd::unique_ptr作为函数参数始终表明这些生命周期的含义).像这样称呼它:

auto a = std::make_shared<A>();

fun(*a);
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以绕过罗嗦*a.get()并直接使用提供的解引用运算符std::shared_ptr.