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

C++中std::unique_ptr已删除函数使用错误问题排查

错误原因分析

你的编译错误核心在于std::unique_ptr的特性:

  • unique_ptr是独占所有权的智能指针,它的拷贝构造函数被显式删除(错误信息中deleted function所指),目的是保证同一时间只有一个unique_ptr持有对象所有权,禁止拷贝行为。
  • 你在find_if的lambda表达式中使用了值传递参数unique_ptr<H> h,这会尝试拷贝容器内的unique_ptr实例传给lambda,而拷贝操作是unique_ptr不允许的,直接触发编译错误。
修正方案

1. 修正Lambda参数类型

将lambda的参数改为const引用,既避免拷贝,又能安全读取对象信息:

auto it = find_if(humans.begin(), humans.end(), [&s](const unique_ptr<H>& h) {
    return h->getName() == s;
});

2. 修正erase的目标迭代器

原代码固定删除humans.begin()不符合需求,应该删除找到的目标迭代器,同时要判断迭代器是否合法(避免未找到元素时的非法访问):

if (it != humans.end()) {
    humans.erase(it);
}
完整修正后的remv方法
void remv(){
    string s;
    cin >> s;
    auto it = find_if(humans.begin(), humans.end(), [&s](const unique_ptr<H>& h) {
        return h->getName() == s;
    }); 
    if (it != humans.end()) {
        humans.erase(it);
    }
}

额外优化提示

基类的纯虚函数getName()建议声明为const成员函数(因为获取名称的操作不应修改对象),子类实现也要对应加上const:

// 基类H
virtual string getName() const = 0;
// 子类P
string getName() const {return this->name;}

这样后续使用const引用的unique_ptr时,也能正常调用该方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:13:29