dimanche 25 septembre 2022

std::move with a function that expects an rvalue reference [duplicate]

I've been doing some examples based around move semantics and I stumbled upon a case that I'm unable to explain and I wasn't able to find a similar question here on stackoverflow either. I suppose there's something obvious that I am not aware of or it's my lack of understanding of the issue as a whole so bear with me.

Let's suppose we have a function:

void func(std::vector<std::string>&& vec)
{
    cout << "Passed vector has " << vec.size() << " elements" << endl;
}

And later some vector is being passed as an argument to it through std::move (that is, basically casting it, I realize that):

std::vector<std::string> v(100);

std::cout << "Before calling the function, vector has " << v.size() << " elements" << std::endl;
func(std::move(v));
std::cout << "After calling the function, vector has " << v.size() << " elements" << std::endl;

It this case, I'm getting the following output (and the elements are still present in the v, at least that's my conclusion upon looking it up under debugger):

Before calling the function, vector has 100 elements
Passed vector has 100 elements
After calling the function, vector has 100 elements

If I change the function and get rid of the rvalue reference, I'm getting the expected result (at least expected to my understanding of move semantics...):

Before calling the function, vector has 100 elements
Passed vector has 100 elements
After calling the function, vector has 0 elements

What am I missing?

Aucun commentaire:

Enregistrer un commentaire