我正在查看 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 variablestr
.
我的问题:示例中的返回类型不应该反过来吗,我的意思是,括号应该形成一个表达式,其类型应该是非引用(或右值引用?);没有括号,说 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/