Home > Net >  Using reference return type function as a rvalue
Using reference return type function as a rvalue

Time:12-13

I am asking what is the difference between string & func and string func in this case.(i.e what changes if I remove ampersand in this case).

string & func(string& a) {
    return a;
}

int main()
{
    string a = "42";
    string b = func(a);

return 0;

}

CodePudding user response:

The ampersand character means that You are passing a reference, not an object. In this case, the function takes a as a reference, and returns another reference to the same object. At the end You still have only one instance of the string.

If You remove the ampersand character, then the function will return a copy of the string You passed in. Then You will have 2 string.

In Your particular example it does not change much, because there is string b = func(a); - it means that the function returns a reference, but using this reference You're making a new copy of the object named b.

CodePudding user response:

The program in the question does not demonstrate the difference between the two. However, here are the differences:

string& func(string& a)

The above function returns a reference to a string. This means that you will be able to change the original string (a in this case) from the return value of func. For example, the following:

func(a) = "some other string"

would modify a and set its value to "some other string". However, the following won't do the same:

string b = func(a);
b = "some other string";

because here b only receives a copy of the string. If the previous block was modified as follows:

string& b = func(a);
b = "some other string";

Then it will also set the value of a to "some other string" because here b itself is a reference to a. In fact, it is equivalent to writing:

string a = "42";
string& temp = a;
string& b = temp;
b = "some other string";

So both temp and b refer to the same string - a.

  • Related