提问人:chunlin yang 提问时间:11/6/2023 最后编辑:wohlstadchunlin yang 更新时间:11/7/2023 访问量:86
我应该如何将一种类型的 std::shared_ptr静态转换为另一种类型的 std::shared_ptr
How should I statically cast a std::shared_ptr of one type to a std::shared_ptr of another
问:
我的代码如下。我想转换为 ,但它没有用。std::shared_ptr<void>
std::shared_ptr<C>
我收到以下错误:
main.cpp:74:63: error: no matching function for call to ‘std::shared_ptr<C>::shared_ptr(std::shared_ptr<void>&)’
std::shared_ptr<C> c = static_cast<std::shared_ptr<C>>(ptr);
我的代码:
class C
{
public:
C() {}
int val;
int set;
};
int main()
{
std::shared_ptr<C> cc = std::make_shared<C>();
cc->val = 1;
cc->set = 2;
std::shared_ptr<void> ptr = cc;
std::shared_ptr<C> c = static_cast<std::shared_ptr<C>>(ptr);
return 0;
}
答:
3赞
wohlstad
11/6/2023
#1
为了将 a 转换为,您需要使用一种特殊的 cast 函数。shared_ptr<X>
shared_ptr<Y>
这些功能:
创建 std::shared_ptr 的新实例,其存储的指针为 使用强制转换表达式从 R 的存储指针获取。
对于静态强制转换,这将是:static_pointer_cast
std::shared_ptr<C> c = std::static_pointer_cast<C>(ptr);
评论
std::static_pointer_cast<C>
static_pointer_cast<std::shared_ptr<C>>