shared_pointer <a href="https://jitcde-common.readthedocs.io/#common-mistakes-and-questions" rel="nofollow noreferrer">further reading</a> <p> <a>

时间:2018-11-12 15:19:22

标签: c++ const shared-ptr const-cast

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?

1 个答案:

答案 0 :(得分:2)

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

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

如果您的函数将更改指针,但您不希望发生这种情况:

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

免责声明:

如果foo修改接收到的指针,则第一个选项会带来风险。

第二个选项将复制整个对象,并需要一个副本构造函数。