This is a two part question. Is it ok to assign the return value of a function to a reference? Such as
Foo FuncBar()
{
return Foo();
}
// some where else
Foo &myFoo = FuncBar();
Is this ok? Its my understanding that FuncBar()
returns a Foo object and now myFoo
is a reference to it.
Second part of the question. Is this an optimization? So if your doing it in a loop a lot of the time is it better to do
Foo &myFoo = FuncBar();
or
Foo myFoo = FuncBar();
And take into account the variables use, won't using the ref require slower dereferences?
A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.
The return type of the function test is string& . This makes it return a reference to the variable str instead of the variable itself. Note how the function call is used on the left side of the assignment statement on line 16. Since the address of str is returned, it can be assigned a value.
In C++ Programming, not only can you pass values by reference to a function but you can also return a value by reference.
A C++ program can be made easier to read and maintain by using references rather than pointers. A C++ function can return a reference in a similar way as it returns a pointer. When a function returns a reference, it returns an implicit pointer to its return value.
Foo &myFoo = FuncBar();
Will not compile. it should be:
const Foo &myFoo = FuncBar();
because FuncBar()
returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const.
Is it safe?
Yes it is safe.
C++ standard specifies that binding a temporary object to a reference to const lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error.
Foo myFoo = FuncBar();
Is Copy Initialization.
It creates a copy of the object returned by FuncBar()
and then uses that copy to initalize myFoo
. myFoo
is an separate object after the statement is executed.
const Foo &myFoo = FuncBar();
Binds the temporary returned by FuncBar()
to the reference myFoo
, note that myFoo
is just an alias to the returned temporary and not a separate object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With