合并两个unique_ptr向量时'use of deleted function'

'use of deleted function' when merging two vectors of unique_ptr

本文关键字:use function deleted of 向量 ptr 两个 unique 合并      更新时间:2023-10-16

我正在尝试合并两个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;
}

您正在尝试从常量Wrapper对象移动。通常,移动语义还要求您要远离的对象是可变的(即不const)。在您的代码中,add_all 方法中 other 参数的类型是 const Wrapper& ,因此other.foos也引用常量向量,您无法离开它。

other 参数的类型更改为 Wrapper& 以使其正常工作。