简体   繁体   English

唯一指针的 C++ 向量

[英]C++ vector of unique pointers

Here is my code:这是我的代码:

class FurnitureShop {
    static const int FURNITURE_RESUPPLY = 50;

    std::string name;
    std::vector<std::unique_ptr<Employee>> employees;
    int completedTasks;

public:
    FurnitureShop(std::string name);
    void addEmployee(std::unique_ptr<Employee> &&employee);
    //...

Attribute of this class 'employees' contains vector of unique pointers.此类“员工”的属性包含唯一指针的向量。 I want to implement method addEmployee:我想实现方法 addEmployee:

void FurnitureShop::addEmployee(unique_ptr<Employee> &&employee) {
    this->employees.insert(employee.operator*());
}

where I suggest method.operator*() should make an access to the first object where unique pointer is.我建议 method.operator*() 应该访问唯一指针所在的第一个对象。 Anyway, as I get result, this is not working well (or as intended).无论如何,正如我得到的结果,这不是很好(或按预期)。 Could you guide me where did I do mistake?你能指导我哪里做错了吗?

employee.operator*() is the same as *employee . employee.operator*()*employee相同。 Which means that you attempt to insert the actual Employee object, not the unique pointer.这意味着您试图插入实际的Employee对象,而不是唯一指针。

You should move the unique pointer object itself into the vector:您应该将唯一指针对象本身移动到向量中:

void FurnitureShop::addEmployee(unique_ptr<Employee> employee) {
    employees.emplace_back(std::move(employee));
}

You are inserting the underlying raw pointer from employee (which in this case remains owned by employee and gets destroyed in the destructor for the std::unique_ptr which is passed as the parameter), while what you want is to move the passed std::unique_ptr itself (since you are already passing an rvalue reference, even though the signatures in your snippet do not match).您正在插入来自employee的底层原始指针(在这种情况下,它仍然由employee拥有,并在作为参数传递的std::unique_ptr的析构函数中被销毁),而您想要的是移动传递的std::unique_ptr本身(因为您已经传递了一个右值引用,即使您的代码段中的签名不匹配)。 What happens now is that you insert the raw pointer and it gets deleted when the function argument gets destroyed.现在发生的是你插入原始指针,当函数参数被销毁时它被删除。

What you want is:你想要的是:

void FurnitureShop::addEmployee(unique_ptr<Employee> &&employee) {
    this->employees.emplace_back(std::move(employee));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM