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

AUD*_*IUV 3 c++ unique-ptr move-semantics deleted-functions c++11

我正在尝试合并两个向量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;
}
Run Code Online (Sandbox Code Playgroud)

jot*_*tik 7

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

更改other参数的类型Wrapper&以使其工作.