jeudi 30 août 2018

C++11 rvalue reference vs const reference

This may be obvious but I think it is something difficult to me. Given this:

void test(std::string&& a) {
    std::cout << "&&" << std::endl;
}

I have read the rvalue reference topic almost 3 times in 2 different books and I came to this conclusion.

 //main
 std::string x{"test"};
 test(std::move(x));

 //output: 
 //&&

This code calls test() with a rvalue reference as parameter so the output is what I expect. Here I am moving around the original value because I use move everywhere. Now look at this:

void test(const std::string& a) {
    std::cout << "&&" << std::endl;
}

If I called the same code I get the same output

//main
std::string x{"test"};
test(std::move(x));

//output: 
//&&

and here I'm tilted.


I know that

int&& s = 5;
const int& s = 5;

is valid because in both cases I provide something that has not an lvalue, it has no addresses. Are && and const& equivalent? If no, are there differences?

Tell me if I am wrong:

  • test(std::string&& a): a is rvalue reference but actually it has an lvalue!

    test(std::string&& a) { something(a) //--> not moved because it has lvalue something(std::move(a)) //now it is moved! }

  • test(const std::string& a): a is const lvalue reference and like before I have lvalue and rvalue. And plus more, in this case if I called

    std::move(a)

where a is a const& the move works!

I am confused. Doesn't move work only for && types?

Aucun commentaire:

Enregistrer un commentaire