What does `auto && i = foo ();` mean

Please explain how automatic type inference works when used with move semantics:

#include <iostream>

template <typename T>
struct A {
    static void type() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};

float& bar() {
    static float t = 5.5;
    return t;
}

int foo() {
    return 5;
}

int main() {
    auto &&a1 = foo();  // I expected auto -> int    (wrong)
    auto &&a2 = bar();  // I expected auto -> float& (correct)

    A<decltype(a1)>::type();
    A<decltype(a2)>::type();
}

Output:

static void A<T>::type() [with T = int&&]
static void A<T>::type() [with T = float&]
+4
source share
2 answers

auto&&(just like T&&in the function template parameter, where Tis the template parameter of this function template) follows slightly different rules than other conclusions - it is informally called the "universal link".

, lvalue X, auto X&. X, auto X. && . X& && X&, X && X&&.

, a1 auto int, a1 int&& , decltype(a1) .

auto a2 float&, a2, decltype(a2).

, , auto -> int , a1 auto &&a1, auto a1.

+3

auto &&a1 = foo();

foo() - int. a1 auto&&, int&&, , a1.

auto &&a2 = bar();

bar() - float &. a2 auto&&, float& && float&, .

:

&& -> &&
&& & -> &
& && -> &
&& && -> &&
+2

Source: https://habr.com/ru/post/1533727/


All Articles