PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] How to tell if Im using by reference correctly?

 July 06, 2022     c++, pass-by-reference, reference     No comments   

Issue

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


Solution

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.



Answered By - Nikos C.
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing