gpt4 book ai didi

c++ - 为什么在使用auto&&it=--vec.end()时自动推导左值引用,是UB吗?

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:36 26 4
gpt4 key购买 nike

请看下面的代码片段:

#include<vector>
using std::vector;
int main()
{
vector<int> a;
auto &&it=--a.end();//what?the hint tell me it deduces a lvalue reference type!
}

我们都知道,当操作数本身是右值时,带有运算符--的自定义类返回一个xvalue,比如--Myclass() 。显然Myclass()右值,所以--Myclass()的返回值也应该是右值(准确地说,xvalue) 也是。
来自 cppref

a.m, the member of object expression, where a is an rvalue and m is a non-static data member of non-reference type;

那么为什么 auto 在这种情况下会推导出左值引用?更重要的是,代码片段可以毫无错误地编译!

为什么右值可以绑定(bind)到左值引用?

我遇到了一个令人困惑的错误(与上面的代码片段不一样,我确定 vector 不为空):稍后当我使用it时,段错误发生了!

The code that causes segment fault (最后三行)这段代码是中文在线测试的答案PAT ,当我提交答案时,它引起段错误。

使用左值引用绑定(bind) --Myclass() 并在以后使用它是否是未定义的行为

最佳答案

We all know that a self-defined class with operator -- returns a rvalue when we write somethin like --Myclass()

不,这不是我们所知道的。从技术上讲,用户定义的前缀递减运算符可以返回对象或引用。在实践中,前缀递减运算符通常返回一个左值引用。

Obviously Myclass() is prvalue, so the return value of --Myclass() should also be prvalue ,too.

这不是值(value)类别传播的方式。您可以在纯右值上调用一个函数,该函数可以返回一个左值(可能返回给 *this)。

So why does the auto deduce lvalue reference in this circumstance?

因为迭代器的自减运算符返回的是左值引用。


使用 auto it 解决问题。


Is it undefined behavior to use lvalue reference to bind a --Myclass() ,and use it later?

取决于 Myclass::operator--() 的声明方式。如果它返回一个左值引用,那么就是 UB。如果它返回一个对象,则没有 UB。可以提供由 ref-qualifier 重载的两种变体。

关于c++ - 为什么在使用auto&&it=--vec.end()时自动推导左值引用,是UB吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49297401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com