Is it safe to refer to function-returned values?

M

Magcialking

Like this:

Type& a=b();

I wonder if the value b returned can be refered this way.
 
A

Alf P. Steinbach

* Magcialking:
Like this:

Type& a=b();

I wonder if the value b returned can be refered this way.

Depends on the definition of Type and the function b().
 
F

Frederick Gotham

Magcialking:
Like this:

Type& a=b();

I wonder if the value b returned can be refered this way.


Firstly, it depends on:

(1) Whether "Type" is a const type or not, e.g. typedef int const Type;

Secondly, it depends on:

(1) Whether the function returns by value or by reference.

If the function returns by reference, then it also depends on:

(1) The lifetime of the object to which it refers.

First thing you'll notice is that you can't bind a "reference to non-
const" to a function invocation which returns by value (or any R-value for
that matter).
Second thing you'll notice is that if the function returns by reference,
then you better make sure that the referred object is still valid after the
function returns. Here's a few examples of good and bad:

int Func1() { return 5; }

int &Func2() { int i = 5; return i; }

int const &Func3() { int const i = 5; return i; }

int main()
{
int &r1 = Func1(); /* Compiler ERROR */

int const &r2 = Func1(); /* OK! */

int &r3 = Func2(); /* Object already destroyed! */

int const &r4 = Func2(); /* Object already destroyed! */

int &r5 = Func3(); /* Compiler ERROR */

int const &r6 = Func3(); /* Object already destroyed! */
}
 
F

Frederick Gotham

Frederick Gotham:
int const &r2 = Func1(); /* OK! */


I should have explained this better. The reason why this is OK is that C++
has special rules for binding a "reference to const" to an R-value.
Specifically, the following:

int const &r = 5;

should behave as if it were:

int const rval = 5;
int const &r = rval;

The return value from a function which returns by value is an R-value.
 
M

Magcialking

Thanks so mush Gotham, this really helped a lot.

"Frederick Gotham дµÀ£º
"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top