我应该如何将一种类型的 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

提问人:chunlin yang 提问时间:11/6/2023 最后编辑:wohlstadchunlin yang 更新时间:11/7/2023 访问量:86

问:

我的代码如下。我想转换为 ,但它没有用。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;
} 
C++ 转换 shared-ptr

评论

0赞 Yksisarvinen 11/6/2023
智能指针具有特殊的强制转换功能
0赞 chunlin yang 11/6/2023
谢谢你的回答。但是,我尝试使用static_pointer_cast。我收到这个错误。我对此一无所知。''' main.cpp:74:67:错误:从“std::shared_ptr<std::shared_ptr<C> >”转换为非标量类型“std::shared_ptr<C>”请求的 std::shared_ptr<C> c = static_pointer_cast<std::shared_ptr<C>>(ptr);```
1赞 wohlstad 11/6/2023
你需要(不是)。std::static_pointer_cast<C>static_pointer_cast<std::shared_ptr<C>>

答:

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);