vendredi 22 juillet 2016

Rvalue references and std::forward

  1. Is there any difference between int&& i = 42; and int i = 42; ?

  2. Regarding std::forward, I read online that "if arg is an lvalue reference, the function returns arg without modifying its type." However the following code:

void f(int& k)
{
    std::cout << "f(int&) " << k << std::endl;
}

void f(int&& k)
{
    std::cout << "f(int&&) " << k << std::endl;
}

int main(void)
{
    int i = 42;
    int& j = i;
    int&& k = 42;

    f(i);
    f(j);
    f(k);

    f(std::forward<int>(i));
    f(std::forward<int>(j));
    f(std::forward<int>(k));
    return 0;
}

prints out

f(int&) 42
f(int&) 42
f(int&) 42
f(int&&) 42
f(int&&) 42
f(int&&) 42

I'm wondering why the 4th and 5th lines aren't f(int&) 42, as per the quote I mentioned above.

Aucun commentaire:

Enregistrer un commentaire