重新启用RVALUE参考变量是合法的吗?
当在单个范围中使用时,为什么要进行编译:
float x = 3.14;
auto &&expr = 2*x + x*x; // expr binds to the result of an expression
expr = x;
“ nofollow noreferrer”就像参考重结合一样,这是L值参考的非法。除此之外, expr
应该“是”表达式的结果。这如何“改变”?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法重新启用顶级参考,就像无法更改顶级const一样。但是当它们在课堂中存在时,您可以从C ++ 20开始。
有了C ++ 20,您可以重新定位参考,但具有很大的陷阱。它们,rvalue和lvalue refs删除默认的分配运算符,因此您必须编写自定义成员功能以使这样的类通常可用。
重新固定的LVALUE参考只需将其与不同的lvalue结合。 RVALUE REFS绑定到没有名称的TMP,因此具有影响其引用的TMP对象寿命的特殊特征。当原始Rvalue Refs的范围结束时,他们的寿命结束了。虽然,如果他们在班级中,它们可以反弹到其他rvalue,该班级对象的范围并不重要。而是终止其生命周期的是初始类对象的范围。
您无法重新启用顶级参考,但是,从C ++ 20开始,您可以重新启动使用
std :: struct_at
。示例LVALUE参考:
这是一个计划,该程序演示了重新构建RVALUE REF的方式并不会延长裁判的寿命,即使其具有更长寿命的对象。
感谢@HolyBlackCat的直截了当,这确实可以反弹。他们甚至可以参考相同的TMP对象。但是观看一生。
另一方面,与LVALUE裁判不同,我想不出一个用于重新介绍课程的用例。而且很少在班上的LVALUE参考。
You can't rebind a top level reference just like you can't change a top level const. But when they exist in classes you can as of c++20.
With c++20 you can rebind references but with significant gotchas. They, rvalue and lvalue refs, delete the defaulted assignment operator so you have to write custom member functions to make such a class generally usable.
Rebinding lvalue refs simply binds it to a different lvalue. rvalue refs bind to a tmp with no name and hence have special characteristics affecting the lifetime of the tmp objects they reference. Their lifetime ends when the scope of the original rvalue refs ends. While, if they are in a class, they can be rebound to a different rvalue the scope of that class object doesn't matter. Rather it's the scope of the initial class object that ends its lifetime.
You can not rebind a top level reference but, as of c++20 you can rebind one that exists in a class using
std::construct_at
.Example lvalue ref:
Here's a program that demonstrates how rebinding an rvalue ref doesn't extend the ref's life even though the object it's rebound to has a longer life.
Thanks to @HolyBlackCat for setting me straight that rvalue refs can, indeed be rebound. They can even refer to the same tmp object. But watch the lifetimes.
On another note, unlike, lvalue refs, I can't think of a use case for rebinding rvalue refs in a class. And only rarely for lvalue refs in a class.