c++ - decltype(auto) 类型推导 : return x vs. return (x)

标签 c++ c++14 auto decltype decltype-auto

我正在查看 isocpp.org FAQ on C++14 language extensions , 阅读 decltype(auto) :

...

Note: decltype(auto) is primarily useful for deducing the return type of forwarding functions and similar wrappers, as shown above, where you want the type to exactly “track” some expression you’re invoking. However, decltype(auto) is not intended to be a widely used feature beyond that. In particular, although it can be used to declare local variables, doing that is probably just an antipattern since a local variable’s reference-ness should not depend on the initialization expression. Also, it is sensitive to how you write the return statement. These two functions have different return types:

decltype(auto) look_up_a_string_1() { auto str = lookup1(); return str;  }
decltype(auto) look_up_a_string_2() { auto str = lookup1(); return(str); }

The first returns string, the second returns string &, which is a reference to the local variable str.

我的问题:示例中的返回类型不应该反过来吗,我的意思是,括号应该形成一个表达式,其类型应该是非引用(或右值引用?);没有括号,说 str 意味着“对 str 的左值引用”。我错了吗?

最佳答案

是的,括号构成了一个表达式。表达式不是引用类型,ever .

If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

“对 T 的引用”表示左值和右值引用。但是表达式确实有一个值类别。 str 作为表达式是左值,(str) 也是左值,因为括号保留类型和值类别。

由于 decltype 在第二种情况下应用于左值表达式,它会产生一个左值引用。

在第一种情况下,id-expressions 的特殊请求规则返回“实体的类型”,这是一个值类型。

关于c++ - decltype(auto) 类型推导 : return x vs. return (x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55825944/

相关文章:

python - 使用 Numpy 读取使用 C++ 数据类型生成的二进制文件

c++ - LNK2005 : "already defined error

c++ - 如何在仍然允许 ADL 等的情况下调用同名的其他函数

c++ - 递归函数扫描字符串添加ASCII

c++ - 将返回类型推导为模板参数方法的类型

c++ - 使期望单个模板参数的模板模板参数的类接受可变模板参数的模板模板参数?

c++ - 在 C++11 中使用 constexpr 和 auto 的冲突声明

c++11 - 如何禁止空列表初始化?

c++ - 为什么 const auto &p{nullptr} 工作,而 auto *p{nullptr} 在 C++17 中不起作用?

c++ - C++ 中 const 自动指针的行为