Setter 对于 std::vector

Setter for std::vector

所以我目前正在为我的学校项目实施设计模式,其中包含 class 模型:

class Model {
    ...

    private:
    biosim::CreatureList list;

    public:
    biosim::CreatureList getList() const;
    void setList(const biosim::CreatureList& list);
};

生物列表:

typedef std::vector<CreatureType> CreatureList;

我想在此 Class 中设置一个包含我的 Creatures 的矢量,以便稍后在 Presenter 中访问它-Class。

首先,我试过:

void Model::setList(const biosim::CreatureList& list) { this->list=list; }

但它给了我以下错误:

'biosim::CreatureType &biosim::CreatureType::operator =(const biosim::CreatureType &)': attempting to reference a deleted function

在我用谷歌搜索后,我发现 post 有人说我应该试试

void Model::setList(const biosim::CreatureList& list) { this->list=std::move(list); }

但它给了我同样的错误。

现在我使用

编译它
void Model::setList(const biosim::CreatureList& list) { this->list.assign(list.begin(), list.end()); }

但我不确定这是否是一个好的解决方案。 有人可以向我解释一下,为什么上面一行会导致错误而最后一行有效吗?更重要的是:最好的方法是什么?

对不起,如果我的英语很烂,那不是我的母语。

如果要存储,按值取:

void Model::setList(biosim::CreatureList list) { 
    this->list = std::move(list);
}

这将复制所有值,因此您还需要提供一种复制 CreatureType 的方法(这就是 CreatureType::operator =(const biosim::CreatureType &) 错误的原因)。

话虽如此,如果您提供一种存储方式,为什么不创建成员 public?

Model m;
m.list = list;

问题是,似乎 CreatureType 类型的元素不是 trivially copyable. 所以你应该实现一个复制/移动构造函数来复制/移动向量中包含的数据(比你可以copy/move向量,因为向量实现了移动语义):

class CreatureType {
  public:
    CreatureType();                // default constructor
    CreatureType(const CreatureType& other);  // copy constructor
    CreatureType(CreatureType&& other); // move constructor
    CreatureType& operator=(const CreatureType& other); // copy operator
    CreatureType& operator=(CreatureType&& other); // move operator

  // ...
};

勾选"The rule of three/five/zero".