gpt4 book ai didi

c++ - 使用 auto&& 完美转发返回值

转载 作者:可可西里 更新时间:2023-11-01 15:16:51 27 4
gpt4 key购买 nike

请引用 C++ 模板:完整指南(第 2 版) 中的这句话:

decltype(auto) ret{std::invoke(std::forward<Callable>(op),
std::forward<Args>(args)...)};
...
return ret;

Note that declaring ret with auto&& is not correct. As a reference, auto&& extends the lifetime of the returned value until the end of its scope but not beyond the return statement to the caller of the function.

作者说 auto&& 不适合完美转发返回值。但是,decltype(auto) 不是也形成了对 xvalue/lvalue 的引用吗?IMO,decltype(auto) 然后遇到同样的问题。那么,作者的意思是什么?

编辑:

上面的代码片段应该放在这个函数模板中。

template<typename Callable, typename... Args>
decltype(auto) call(Callable&& op, Args&&... args) {
// here
}

最佳答案

这里有两个推论。一个来自返回表达式,一个来自 std::invoke表达。因为 decltype(auto) is deduced to be the declared type for unparenthesized id-expression , 我们可以关注从 std::invoke 中的推论表达。

引自[dcl.type.auto.deduct] paragraph 5:

If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone. The type deduced for T is determined as described in [dcl.type.simple], as though e had been the operand of the decltype.

并引用自[dcl.type.simple] paragraph 4 :

For an expression e, the type denoted by decltype(e) is defined as follows:

  • if e is an unparenthesized id-expression naming a structured binding ([dcl.struct.bind]), decltype(e) is the referenced type as given in the specification of the structured binding declaration;

  • otherwise, if e is an unparenthesized id-expression or an unparenthesized class member access, decltype(e) is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;

  • otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;

  • otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;

  • otherwise, decltype(e) is the type of e.

备注decltype(e)推导为 T而不是 T&&如果e是纯右值。这是与 auto&& 的区别.

所以如果std::invoke(std::forward<Callable>(op), std::forward<Args>(args)...)是纯右值,例如 Callable 的返回类型不是引用,即按值返回,ret被推导为同一类型而不是引用,完美转发了按值返回的语义。

关于c++ - 使用 auto&& 完美转发返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49033889/

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