You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将std::shared_ptr<void>静态转换为std::shared_ptr<C>?

解决std::shared_ptr转std::shared_ptr的编译错误

你遇到的编译错误是因为不能直接用static_cast转换std::shared_ptr对象,C++标准针对智能指针提供了专门的类型转换模板函数。

正确做法

使用std::static_pointer_cast替代普通的static_cast,它是C++标准库为std::shared_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::static_pointer_cast进行转换
    std::shared_ptr<C> c = std::static_pointer_cast<C>(ptr);
    return 0;
}

补充说明

因为你的std::shared_ptr<void>是从std::shared_ptr<C>转换而来的,所以用std::static_pointer_cast是安全的,它能保证类型转换的正确性。如果是不确定原指针类型的场景,可以考虑使用std::dynamic_pointer_cast(需要目标类型有虚函数支持),但当前场景下std::static_pointer_cast完全适用。

内容的提问来源于stack exchange,提问作者chunlin yang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:52:02