What is the difference between auto and decltype(auto) when returning from a function?

C++C++14

C++ Problem Overview


I rarely see decltype(auto) but when I do it confuses me because it seems to do the same thing as auto when returning from a function.

auto g() { return expr; }
decltype(auto) g() { return expr; }

What is the difference between these two syntaxes?

C++ Solutions


Solution 1 - C++

auto follows the template argument deduction rules and is always an object type; decltype(auto) follows the decltype rules for deducing reference types based on value categories. So if we have

int x;
int && f();

then

expression    auto       decltype(auto)
----------------------------------------
10            int        int
x             int        int
(x)           int        int &
f()           int        int &&

Solution 2 - C++

auto returns what value-type would be deduced of you assigned the return clause to an auto variable. decltype(auto) returns what type you would get if you wrapped the return clause in decltype.

auto returns by value, decltype maybe not.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontemplate boyView Question on Stackoverflow
Solution 1 - C++Kerrek SBView Answer on Stackoverflow
Solution 2 - C++Yakk - Adam NevraumontView Answer on Stackoverflow