tags:

views:

98

answers:

2

Will fnc like this extend returned object lifetime? If not, are there a ways to do so?

 const int& f () //<<----Here you see, I'm returning by ref to const int
 {
     return 1;
 }
+3  A: 

No, it won't extend the object lifetime.

You can't extend the lifetime of the temporary (a temporary is created for binding to the reference), but, you can simply do

int f() { return 1; }

:-)

Cheers & hth.,

– Alf

Alf P. Steinbach
flownt
@flownt: Sorry, no, what happens then is, from a formal POV that a new reference is created for an indeterminate value. In practice that will be the original `int` (it has not, in practice, yet had the time to be garbled). However, if you try that trick with an object of a type with destructor you may be in a for a nasty surprise...
Alf P. Steinbach
@Alf P. Steinbach: i'm not sure wheather the standard actually demands it, but because of RVO, there's no reason to delete prematurely and therefore gcc won't
flownt
@flownt: The standard supports RVO (by allowing copy construction to be elided) but it doesn't require RVO. Extending the lifetime of a local by returning a reference to it can work through RVO, but it's then just a case of Undefined Behavior doing what one what one would like it to do, with a particular compiler with particular options. UB can do anything, including very undesirable things.
Alf P. Steinbach
+2  A: 

I don't think this will compile (with a constant) but if you get something similar compiled it will fail runtime with undefined behaviour.

It will not extend any lifetime so you are returning a ref to a var/const that no longer exists.

Henk Holterman
It must compile, by the language rules. They make no exception about binding for a reference that's a function result (although a good compiler may warn). But yes, to the second para. :-)
Alf P. Steinbach
@Alf: yeah, I was misreading the `const` .
Henk Holterman