c++ - 返回左值的函数,总是返回左值引用

标签 c++

有效 C++ 的第 3 项中的 Scott meyers 说

Applying decltype to a name yields the declared type for that name. Names are typically lvalue expressions, but that doesn’t affect decltype’s behavior. For lvalue expressions more complicated than names, however, decltype generally ensures that the type reported is an lvalue reference. That is, if an lvalue expression other than a name has type T, decltype reports that type as T&. This seldom has any impact, because the type of most lvalue expressions inherently includes an lvalue reference qualifier. Functions returning lvalues, for example, always return lvalue references.


他说函数返回左值是什么意思,例如,总是返回左值引用

最佳答案

这意味着它所说的!
没有办法使函数返回类型不是 T& ,但调用它会产生一个左值表达式。
每个其他返回类型都会导致函数调用成为右值表达式。
当你考虑到“返回”已经存在的东西的唯一方法是通过引用时,这是很直观的——函数调用的结果总是“临时的”,无论是因为它正在复制一些局部变量,还是因为它从一些局部变量。
此规则的可能异常(exception),返回 T&& , 也不适用,因为它们会产生右值表达式(这就是移动语义起作用的原因,因为只有右值表达式才能继续绑定(bind)到 T&& 参数)。
Scott 正在报告语言规则的结果,并告诉我们同样的结果被用作 decltype 规则之一的理由。 .
可以说,他可以更清楚地表达出来:

The only functions whose calls evaluate to lvalues, are those that return lvalue references.

关于c++ - 返回左值的函数,总是返回左值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64862374/

相关文章:

c++ - Valgrind 调试结果不显示发生错误的行数

c++ - 获取类成员变量的内存地址(非动态)

C++ 表达式必须有常量值

c++ - 如何判断 `constexpr`是否在编译时求值(无需人工检查)

c++ - 在多个线程中从列表中删除元素

c++ - 为什么我会收到以下错误 : In constructor 'B::B(int, int)' : no matching function for call to 'A::A()'

c++ - 当我在 c++ 中使用系统 ("command") 时,我可以调用 cygwin 而不是普通命令行吗?

c++ - 引用模板参数类型的 static_assert

c++ - 设置精度无法正常工作

C++ 字符数组 : a[i] = b[i] fails