后续行动。是返回对 x++ 的引用定义?
我最近问了一个问题 return x++; 的行为是?定义?
结果与我的预期一致,但让我思考类似的情况。
如果我写
class Foo
{
...
int x;
int& bar() { return x++; }
};
Where bar now returns an int引用,这个行为是否定义了?如果上一个问题的答案实际上是正确的,而不仅仅是对正在发生的事情的方便抽象,那么您似乎会返回对堆栈变量的引用,该堆栈变量在执行返回后就会被销毁。
如果它只是一个抽象,我很想知道后增量实际上保证了什么行为。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你不能这样做,因为这会返回对临时对象的引用。
No, you cannot do that, as that would be returning a reference to a temporary.
您的代码将导致
编译错误
。但是,如果将后增量更改为前增量,它就会起作用。x
的值递增,然后返回对此修改后的x
的引用。当前代码的问题是您正在尝试修改临时对象,而这是不允许的,因为它们是临时对象。
从这个 有关右值引用的 Visual C++ 博客文章
Your code will result in
compilation error
. But if you change the post-increment to pre-increment it works. The value ofx
is incremented and then a reference to this modifiedx
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