Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

function - C++: Argument Passing "passed by reference"

I understand as with any other variable, the type of a parameter determines the interaction between the parameter and its argument. My question is that what is the reasoning behind why you would reference a parameter vs why you wouldn't? Why are some functions parameters reference and some are not? Having trouble understanding the advantages of doing so, could someone explain?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The ability to pass by reference exists for two reasons:

  1. To modify the value of the function arguments
  2. To avoid make copies of an object for performance reasons

Example for modifying the argument

void get5and6(int *f, int *s)  // using pointers
{
    *f = 5;
    *s = 6;
}

this can be used as:

int f = 0, s = 0;
get5and6(&f,&s);     // f & s will now be 5 & 6

OR

void get5and6(int &f, int &s)  // using references
{
    f = 5;
    s = 6;
}

this can be used as:

int f = 0, s = 0;
get5and6(f,s);     // f & s will now be 5 & 6

When we pass by reference, we pass the address of the variable. Passing by reference is similar to passing a pointer - only the address is passed in both cases.

For eg:

void SaveGame(GameState& gameState)
{
    gameState.update();
    gameState.saveToFile("save.sav");
}

GameState gs;
SaveGame(gs)

OR

void SaveGame(GameState* gameState)
{
    gameState->update();
    gameState->saveToFile("save.sav");
}

GameState gs;
SaveGame(&gs);


Since only the address is being passed, the value of the variable (which could be really huge for huge objects) doesn't need to be copied. So passing by reference improves performance especially when:
  1. The object passed to the function is huge (I would use the pointer variant here so that the caller knows the function might modify the value of the variable)
  2. The function could be called many times (eg. in a loop)

Also, read on const references. When it's used, the argument cannot be modified in the function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...