Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Follow-up. Is return reference to x++ defined?

I recently asked the question Is the behavior of return x++; defined?

The result was about what I expected, but got me thinking about a similar situation.

If I were to write

class Foo
{   
  ...   
  int x;   
  int& bar() { return x++; }
};

Where bar now returns an int reference, is this behavior defined? If the answer to the previous question is literally true and not just a convenient abstraction of what's going on, it would seem you'd return a reference to a stack variable that would be destroyed as soon as the return was executed.

If it is just an abstraction, I'd be interested to know what behavior is actually guaranteed by a post-increment.

like image 679
patros Avatar asked Jan 30 '26 17:01

patros


1 Answers

No, you cannot do that, as that would be returning a reference to a temporary.

like image 59
Tronic Avatar answered Feb 01 '26 07:02

Tronic