加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 合并unique_ptr的两个向量时’使用已删除的函数’

发布时间:2020-12-16 10:02:35 所属栏目:百科 来源:网络整理
导读:我正在尝试合并unique_ptr的两个向量(即std ::将它们从一个移出到另一个)并且我继续遇到“使用已删除的函数…”错误文本的墙.根据错误,我显然试图使用unique_ptr的删除拷贝构造函数,但我不确定为什么.以下是代码: #include vector#include memory#include a
我正在尝试合并unique_ptr的两个向量(即std ::将它们从一个移出到另一个)并且我继续遇到“使用已删除的函数…”错误文本的墙.根据错误,我显然试图使用unique_ptr的删除拷贝构造函数,但我不确定为什么.以下是代码:

#include <vector>
#include <memory>
#include <algorithm>
#include <iterator>

struct Foo {
    int f;

    Foo(int f) : f(f) {}
};

struct Wrapper {
    std::vector<std::unique_ptr<Foo>> foos;

    void add(std::unique_ptr<Foo> foo) {
        foos.push_back(std::move(foo));
    }

    void add_all(const Wrapper& other) {
        foos.reserve(foos.size() + other.foos.size());

        // This is the offending line
        std::move(other.foos.begin(),other.foos.end(),std::back_inserter(foos));
    }
};

int main() {
    Wrapper w1;
    Wrapper w2;

    std::unique_ptr<Foo> foo1(new Foo(1));
    std::unique_ptr<Foo> foo2(new Foo(2));

    w1.add(std::move(foo1));
    w2.add(std::move(foo2));

    return 0;
}

解决方法

你试图从一个常量的Wrapper对象移动.通常,移动语义还要求您移动的对象是可变的(即不是const).在你的代码中,add_all方法中另一个参数的类型是const Wrapper&amp ;,因此other.foos也指一个常量向量,你不能离开它.

将其他参数的类型更改为Wrapper&使它工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读