9

Is this safe?

const int& f()
{
return 1;
}

What I'm trying to do is to return a some value to const &

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
smallB
  • 16,662
  • 33
  • 107
  • 151
  • 2
    Why would you want to do this? – R. Martinho Fernandes Aug 01 '11 at 09:20
  • possible duplicate of [Is it more efficient to return a const reference](http://stackoverflow.com/questions/275795/is-it-more-efficient-to-return-a-const-reference) – iammilind Aug 01 '11 at 09:22
  • possible duplicate of [C++ Pass By Const Reference and Return By Const Reference](http://stackoverflow.com/questions/3216948/c-pass-by-const-reference-and-return-by-const-reference) – stijn Aug 01 '11 at 09:34

2 Answers2

10

It is not okay.
Returning reference to a temporary is not okay because accessing it outside the function causes Undefined Behavior.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 1
    @mkaes: what Steve Jessop said. The technical reason is that lifetime extension of a function result reference, in practice would be extremely costly. The implementation would have to support return of a reference to e.g. a static variable inside the function, but would also have to make sure that in other cases storage was allocated and ideally deallocated after the reference disappeared, preferably in a way that would be transparent to the calling machine code. I don't think that that's theoretically impossible. But if it's technically possible, then in practice it would be *very* costly... – Cheers and hth. - Alf Aug 01 '11 at 11:24
  • @Steve: Agreed. I should read more carefully. Removed wrong comment – mkaes Aug 02 '11 at 07:55
  • Is `1` a temporary? `int x=1; return x;` would return a temporary, but `return 1` is different, I think. Where does the `1` live? Perhaps all literals live is a 'static' space where they are safe forever. For example `const char * foo() { return "Am I temporary?"; }` – Aaron McDaid Dec 20 '11 at 20:27
  • Only string literals live in that space. Other literals do not live in that space. – Puppy May 31 '15 at 17:23
  • Curious as to why my compiler (GCC) doesn't issue a warning in this case. Any ideas? Edit: GCC raises "warning: returning reference to temporary [-Wreturn-local-addr]" – ttb Jul 04 '17 at 18:50
2

No, you're returning a reference to a temporary variable - this is not safe. The temporary variable will have been destroyed upon function return.

sharptooth
  • 167,383
  • 100
  • 513
  • 979