【问题标题】:'use of deleted function' when merging two vectors of unique_ptr合并 unique_ptr 的两个向量时“使用已删除函数”
【发布时间】:2016-08-17 22:24:23
【问题描述】:

我正在尝试合并unique_ptr 的两个向量(即std::move 它们从一个向量到另一个向量)并且我一直遇到“使用已删除函数...”的错误文本墙。根据错误,我显然正在尝试使用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;
}

【问题讨论】:

    标签: c++ c++11 move-semantics unique-ptr deleted-functions


    【解决方案1】:

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

    other参数的类型更改为Wrapper&amp;使其工作。

    【讨论】:

    • 谢谢!这似乎已经做到了!我认为移动语义的可变性是有道理的,因为其他向量将因此而无效。
    • @AUD_FOR_IUV 欢迎来到 Stack Overflow! :-)
    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多