[英]shared_ptr<const A> to shared_pointer<A>
I have a function which returns a shared pointer of type const A
. 我有一个函数返回const A
类型的共享指针。
std::shared_ptr< const A> getPointer() const;
and I have a function which needs a shared_ptr of type A
. 我有一个需要A
类型的shared_ptr的函数。
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 >' 错误:从 'shared_ptr的<常量A>' 到 '的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. 这行代码位于GUI中,并且绝对不属于任何热门代码。 (This means I do not care if I create a copy of A
or not) (这意味着我不在乎是否创建A
的副本)
What is the easiest solution to fix this? 解决此问题的最简单解决方案是什么?
https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast 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. 如果foo修改接收到的指针,则第一个选项会带来风险。
The second option makes a copy of the entire object and requires a copy constructor. 第二个选项复制整个对象,并需要一个复制构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.