gpt4 book ai didi

c++ - 合并 unique_ptr 的两个 vector 时“使用已删除的函数”

转载 作者:太空狗 更新时间:2023-10-29 20:10:48 34 4
gpt4 key购买 nike

我正在尝试合并 unique_ptr 的两个 vector (即 std::move 它们从一个 vector 移到另一个 vector 中),我一直遇到“使用已删除的功能...”错误文本墙。根据错误,我显然是在尝试使用 unique_ptr 的 deleted copy constructor,但我不确定为什么。下面是代码:

#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 对象 move 。通常, move 语义还要求您要 move 的对象是可变的(即不是 const)。在您的代码中,add_all 方法中的 other 参数的类型是 const Wrapper&,因此 other.foos 也是指的是一个常量 vector ,你不能离开它。

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

关于c++ - 合并 unique_ptr 的两个 vector 时“使用已删除的函数”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825148/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com