C++ Returning reference to local variable

前端 未结 3 1920
一个人的身影
一个人的身影 2020-11-21 07:25

Is the following code (func1()) correct if it has to return i? I remember reading somewhere that there is a problem when returning reference to a local variable. How is it d

3条回答
  •  面向向阳花
    2020-11-21 07:47

    A good thing to remember are these simple rules, and they apply to both parameters and return types...

    • Value - makes a copy of the item in question.
    • Pointer - refers to the address of the item in question.
    • Reference - is literally the item in question.

    There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int* and returning &i would have been equally incorrect. You would be better off in that case doing this...

    void func1(int& oValue)
    {
        oValue = 1;
    }
    

    Doing so would directly change the value of your passed in parameter. Whereas this code...

    void func1(int oValue)
    {
        oValue = 1;
    }
    

    would not. It would just change the value of oValue local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue, and not oValue itself.

提交回复
热议问题