Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Almost Always decltype(auto)?

decltype(auto) can deduce a value and a reference. auto never deduces a reference. It sounds to me for generic code and optimization decltype(auto) should always be preferred. Is this the case? Consider for example returning an object which may or may not be copyable. auto& is required to avoid copying it, but that forces it to be a reference always. decltype(auto) is the correct option in this case. What are the disadvantages of decltype(auto) aside from being more typing?

like image 456
user4394799 Avatar asked Dec 26 '14 03:12

user4394799


1 Answers

From the isocpp C++14 FAQ on 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. 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); }
like image 78
Pradhan Avatar answered Oct 04 '22 10:10

Pradhan