简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM