Whats the significance of return by reference?

后端 未结 11 1220
既然无缘
既然无缘 2021-02-13 00:15

In C++,

function() = 10;

works if the function returns a variable by reference.

What are the use cases of it?

11条回答
  •  生来不讨喜
    2021-02-13 01:07

    Consider the following code, MyFunction returns a pointer to an int, and you set a value to the int.

    int  *i;
    i = MyFunction();
    *i = 10;
    

    Now shorten that to

    *(MyFunction()) = 10;
    

    It does exactly the same thing as the first code block.

    You can look at a reference as just a pointer that's always dereferenced. So if my function returned a reference - not a pointer - to an int the frist code block would become

    int  &i;
    i = MyFunction();
    i = 10;
    

    and the second would become

    MyFunction() = 10;
    

    This is what i was looking for

提交回复
热议问题