所以我有一个函数,可以在向量中设置变量,并返回可修改的单元格引用。但是我不确定我是否正确使用了引用“&”,因为我有两个有效的示例。例1:
Cell& Grid::set(const int x, const int y, const Cell & value) {
int index = get_index(x, y);
this->grid[index] = value;
return this->grid[index];
}
Ex2:
Cell& Grid::set(const int x, const int y, const Cell value) {
int index = get_index(x, y);
this->grid[index] = value;
return this->grid[index];
}
哪种方法是正确的,我如何告诉未来?
编辑:单元格是枚举而不是对象
由于以下原因,这是value
参数的接收器功能:
grid[index] = value;
因此,在这种情况下,您应该传递非常量值并将其移至grid
:
Cell& Grid::set(const int x, const int y, Cell value)
{
grid[get_index(x, y)] = std::move(value);
return grid[index];
}
但是您应该确保Cell
是可移动类型,因为如果不是,则会花费额外的副本。
这是接收器功能使用的常用模式。 (意味着将参数存储在比函数调用本身更久的地方的函数。)