views:

112

answers:

2

I recently asked the question http://stackoverflow.com/questions/2380803/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.

+5  A: 

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

Tronic
int x is a member variable, not a temporary
John Knoeller
@John: that's true, but the thing the function is returning (the result of `x++`) *is* a temporary, since it's not the same as the (new) value of `x`.
Greg Hewgill
jakebman
jakebman
@Greg: Thanks, that's clearer now. I missed the invisible temporary. I was thinking that you would still end up with a reference to x.
John Knoeller
A: 

Your code will result in compilation error. But if you change the post-increment to pre-increment it works. The value of x is incremented and then a reference to this modified x is returned.

The problem with the current code is that you are trying to modify temporary and this is not allowed for the very reason that they are temporary objects.

From this Visual C++ blog article about rvalue references

... C++ doesn't want you to accidentally modify temporaries....

codaddict