C++: Argument Passing “passed by reference”

前端 未结 4 1716
忘了有多久
忘了有多久 2020-11-27 16:24

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 reasonin

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 16:54

    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.

提交回复
热议问题