Search code examples
c++constantsshared-ptrconst-cast

shared_ptr<const A> to shared_pointer<A>


I have a function which returns a shared pointer of type const A.

std::shared_ptr< const A> getPointer() const;

and I have a function which needs a shared_ptr of type A.

void foo(std::shared_ptr<A> a);

When I try to call my function I get the following message:

error: no viable conversion from 'shared_ptr< const A>' to 'shared_ptr< A >'

I do not care about performance. This line of code is in a GUI and by all means not part of any hot code. (This means I do not care if I create a copy of A or not)

What is the easiest solution to fix this?


Solution

  • https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast

    foo(std::const_pointer_cast<A>(getPointer()));
    

    If your function will alter the pointer and you do not wish for this to happen:

    auto ptr = std::make_shared<A>(*(getPointer().get()));
    foo(ptr);
    

    Disclaimer:

    The first option presents the risk if foo modifies the received pointer.

    The second option makes a copy of the entire object and requires a copy constructor.