后续行动。是返回对 x++ 的引用定义?

发布于 2024-08-23 15:15:57 字数 430 浏览 16 评论 0原文

我最近问了一个问题 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海夜未眠 2024-08-30 15:15:57

不,你不能这样做,因为这会返回对临时对象的引用。

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

深爱不及久伴 2024-08-30 15:15:57

您的代码将导致编译错误。但是,如果将后增量更改为前增量,它就会起作用。 x 的值递增,然后返回对此修改后的 x 的引用。

当前代码的问题是您正在尝试修改临时对象,而这是不允许的,因为它们是临时对象。

从这个 有关右值引用的 Visual C++ 博客文章

...C++ 不希望您意外修改临时变量...

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....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文