Difference between returning reference vs returning value C++

前端 未结 3 1914
长发绾君心
长发绾君心 2020-12-02 01:29

Question about why is it necessary at all to return a reference from a function.

Following code behaves exactly the same, if we replace int& with

相关标签:
3条回答
  • 2020-12-02 01:42

    The difference is that, when you return a reference, you can assign to the result of GetVal():

    myObj.GetVal() = 42;
    

    You can also keep the returned reference around, and use it to modify myObj.val later.

    If GetVal() were to return val by value, none of this would be possible.

    Whether any of this is desirable, or indeed good design, is a different question altogether.

    Note that your example is very different to the code in the linked question -- that code returns an invalid reference and is unequivocally a bad idea.

    0 讨论(0)
  • 2020-12-02 01:50

    In this case the difference is that returning by reference allows caller to modify the data member by assigning value to it, while returning by value returns caller only a copy of the variable.

    First allows you to write:

    myObj.GetVal() = 100;
    

    While the latter doesn't.

    Note that the first in a way allows caller of the function to obtain a reference to a private data member and they can modify it at will. For me this is something which i like to avoid. I do not want users of my class to change the state of my class members at their will.

    0 讨论(0)
  • 2020-12-02 02:02

    Unless you return a reference code like this will be illegal

    int main()
    {
        myClass myObj(666);
        myObj.GetVal() = 777;
        return 0;
    }
    

    So an important question is whether you want code like that to be legal. In this case I would say not, but other cases may be different.

    For your other point you are nearly right, but it's not about whether the user can see the variable, it's about the lifetime of the variable. The user might not be able to see the variable (it might be private for instance) but as long as the variable is still alive then returning a reference to it is not an error.

    For complex objects there is also the issue of whether you want to copy the object or return a refernece to the original. That's less likely to be an issue with simple types like int however.

    0 讨论(0)
提交回复
热议问题