如何判断我是否正确使用引用?

How to tell if Im using by reference correctly?

所以我有一个函数,它在向量中设置一个变量,returns 返回一个可修改的单元格引用。但我不确定我是否正确使用了引用“&”,因为我有两个有效的示例。 示例 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];
}

哪种方法是正确的,我如何判断未来?

编辑:Cell 是枚举而不是对象

这是value参数的sink函数,因为:

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 是可移动类型,因为如果不是,将花费您额外的副本。

这是在接收函数方面使用的常见模式。 (意思是将参数存储在函数调用本身之外的某个地方的函数。)

另请参阅 另一个关于何时通过引用传递有益的问题。