Search code examples
c++returndefinedpost-increment

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.


Solution

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