开发者

What executes earlier, return or ++?

class x
{
 public:
  int y;
  x& operator++(int);

};

I want the foo(), that works like:

int& foo()
{
  int& ret_val = x.y;
  x++;
  return ret_val;
}

but looks like:

int& foo()
{
  return (x++).y;
}

Is this possible? What is executed earlier, return or ++?

ok, thx for your answers.

"rather a copy of the object in the state prior to the increment (i.e.- your x& operator++(int) doesnt follow the convention)" Can I write operator++(int) follow the convention? a开发者_运维技巧nd how do it be written?

Then can I write function like this:

int foo() {return (x++).y;}


The ++ executes before the return, but the return value is fixed before the ++. I started to write out the equivalent code but then I realized your middle example is already the same as what you want to do.


The ++ operator will be executed earlier.


Your final implementation is wrong, and should not compile, because you are trying to form a non-const reference to a temporary. There are many cases of dangling references, all of which are incorrect, but this one at least can be caught by the compiler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜