1

So I have a function which sets a variable in a vector and returns a modifiable cell reference back. But I'm unsure if I am using the reference '&' correctly as I have two examples that work. Ex1:

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];
}

Which would be the correct way and how can I tell for the future?

Edit: Cell is an enum not an object

Ellis Thompson
  • 408
  • 6
  • 18

1 Answers1

1

This is a sink function for the value parameter, because of this:

grid[index] = value;

So in this case, you should be passing by non-const value and move it into grid:

Cell& Grid::set(const int x, const int y, Cell value)
{
    grid[get_index(x, y)] = std::move(value);
    return grid[index];
}

You should make sure that Cell is a movable type though, because if it isn't, it will cost you an extra copy.

This is the common pattern that is used when it comes to sink functions. (Meaning functions that store arguments somewhere that outlives the function call itself.)

Also take a look at another relevant answer to a different question on when it's beneficial to pass by reference.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96