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

为何将Derived类unique_ptr赋值给Base类的代码无法编译?

问题:派生类unique_ptr赋值给基类unique_ptr时编译报错

代码示例

#include <memory>

struct Base {
};

struct Derived: Base {
    int n;
};

int main() {
    std::unique_ptr<Base> base_ptr = std::make_unique<Derived>(5);
}

编译器报错信息(翻译后)

/usr/include/c++/13/bits/unique_ptr.h:1070:30: 错误:无法将‘std::forward<int>((* & __args#0))’从‘int’类型转换为‘arb::exchange_connector::Base’类型
  1070 |     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }

错误原因与解决方法

你误解了报错根源:问题不在unique_ptr的赋值逻辑上(你查看的源码确实支持派生类unique_ptr向基类的移动),而是std::make_unique<Derived>(5)无法创建Derived对象——你的Derived类没有定义接受int参数的构造函数。

编译器尝试构造Derived对象时,找不到匹配的构造函数,进而触发了类型转换错误。

修复步骤:

  1. 给Derived添加接受int的构造函数:
struct Derived: Base {
    int n;
    // 显式构造函数初始化成员n
    explicit Derived(int val) : n(val) {}
};
  1. (可选但建议)为基类添加虚析构函数,避免后续处理集合时出现内存泄漏:
struct Base {
    virtual ~Base() = default;
};

修改后代码即可正常编译,实现将不同派生类消息的unique_ptr存入基类unique_ptr集合的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:40:11