Search code examples
c++shared-ptrsmart-pointers

function call with shared pointer whose object should be const


I have a variable a whose type is A.

A a;

I want to call a function which takes a const reference of type A as an input argument.

fun(const A &a);

After some code changes I decided it is best to change the type of variable a to std::shared_ptr<A>

std::shared_ptr<A> a;

What is the best way to change function fun so that I make sure that object a is never changed (it should remain const)?

should fun remain as it is and I should call it like:

fun(*a.get())

or is there any alternative? Somehow this feels ugly to me...

I guess simply changing fun to fun(const std::shared_ptr<A> &a) will not work because I want to make sure that the function does not change the underlying object and not the shared pointer.

I cannot use std::shared_ptr<const A> a because it is necessary to change variable a at some point.


Solution

  • As void fun(const A& a); doesn't seem to have any implications on the lifetime of the argument, leave the signature as it is now (passing std::shared_ptr or std::unique_ptr as a function argument always suggests those lifetime implications). Call it like this:

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

    This way, you can get around the wordy *a.get() and directly use the dereference operator provided by std::shared_ptr.