Alex Rivera | Logout

Assign return value from function to a reference c++?

Asked 2012-10-05T07:00:07.343
19

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?

Edit
Report

1 Answer

26
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.

answered 2012-10-05T07:05:39.597

Your Answer