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?
Will not compile. it should be:
because
FuncBar()returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const.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.
Is Copy Initialization.
It creates a copy of the object returned by
FuncBar()and then uses that copy to initalizemyFoo.myFoois an separate object after the statement is executed.Binds the temporary returned by
FuncBar()to the referencemyFoo, note thatmyFoois just an alias to the returned temporary and not a separate object.