gpt4 book ai didi

c++ - 带有标准容器的 unique_ptr : attempting to reference a deleted function

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

我正在尝试将 unique_ptr 与任何 STL 容器一起使用(实际上我更喜欢列表),我看到 unique_ptr 需要移动语义。员工是基类的这段代码:

typedef std::unique_ptr<employee> p_employee;

std::list<p_employee> make_test_array() {
std::list<p_employee> objects = {
p_employee(new accounter(...)),
p_employee(new engineer(...)),
p_employee(new developer(...))
};

return objects;
}

你知道我在做什么——只是从一个函数返回这个列表

那么有能力做到这一点吗?什么是正确的技术?

最佳答案

您正在尝试构建 std::list<p_employee>使用 std::list采用 std::initializer_list<p_employee> 的构造函数争论。

不幸的是,std::initializer_list只允许 const访问其元素,这意味着编译器将尝试复制每个 p_employee (或 std::unique_ptr<employee> )失败,因为 unique_ptr是只能移动的类型,不能被复制。

如果您将 braced-init-list 替换为一系列 emplace_back,您的代码应该可以正常工作/push_back电话。

std::list<p_employee> make_test_array() {
std::list<p_employee> objects;

objects.emplace_back(new accounter(...));
objects.push_back(p_employee(new engineer(...))); // the exception safe alternative
// and so on

return objects;
}

关于c++ - 带有标准容器的 unique_ptr : attempting to reference a deleted function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28786751/

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