gpt4 book ai didi

c++ - 几乎总是 decltype(auto)?

转载 作者:IT老高 更新时间:2023-10-28 23:19:23 24 4
gpt4 key购买 nike

decltype(auto) 可以推导出一个value和一个referenceauto 从不推断 reference。在我看来,通用代码和优化 decltype(auto) 应该始终是首选。是这样吗?例如,考虑返回一个对象,该对象可能是可复制的,也可能是不可复制的。 auto& 是避免复制它所必需的,但这会强制它始终是一个引用。 decltype(auto) 在这种情况下是正确的选项。 decltype(auto)除了打字多了还有什么缺点?

最佳答案

来自 decltype(auto) 上的 isocpp C++14 常见问题解答:

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. look_up_a_string_1 returns a string while look_up_a_string_2 returns a string&.

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

关于c++ - 几乎总是 decltype(auto)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27652452/

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