复制分配运算符,向量

时间:2018-11-14 16:58:10

标签: c++ c++11 copy-assignment

我有一个保存值的向量(不在堆上!)

std::vector<Dish> menu;

我想像这样实现拷贝分配操作符:

    Restaurant &Restaurant::operator=(Restaurant &&other) {
    if (this == &other)
        return *this;
    open = other.open;

    menu = std::move(other.menu);
}

我得到那些错误/警告:

        ^
/Users/avivlevitzky/CLionProjects/SPL-Project-1/Restaurant.cpp:49:10: note: in instantiation of member function 'std::__1::vector<Dish, std::__1::allocator<Dish> >::operator=' requested here
    menu = other.menu;
         ^
/Users/avivlevitzky/CLionProjects/SPL-Project-1/Dish.h:18:15: note: copy assignment operator of 'Dish' is implicitly deleted because field 'id' is of const-qualified type 'const int'
    const int id;

怎么了?

1 个答案:

答案 0 :(得分:0)

这是移动任务,所以移动对象:

open = std::move(other.open);
menu = std::move(other.menu);

openmenu可能不允许复制,因此会出现错误。

您不需要清除menu,因为您正在用另一个对象替换内容。