0

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)
{
    std::cout << "Passed vector has " << vec.size() << " elements" << std::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?

  • The object is left in unspecified state. See [this](https://stackoverflow.com/a/70480152/12002570) which says: *"Unless otherwise specified, all standard library objects that have been moved from are placed in a "valid but unspecified state","*. Also see [Is a moved-from vector always empty?](https://stackoverflow.com/questions/17730689/is-a-moved-from-vector-always-empty) – Jason Sep 25 '22 at 11:21
  • `move` doesn't actually move, it's just a cast to enable move semantics. Case 1 you pass a reference and don't change it. Case 2 actually move constructs an argument emptying the original. – François Andrieux Sep 25 '22 at 11:23
  • The name is a little misleading, because [`std::move`](https://en.cppreference.com/w/cpp/utility/move) doesn't actually move anything. All it really does is cast the value to an rvalue reference. – Some programmer dude Sep 25 '22 at 11:23
  • 2
    @JasonLiam For `vector`s move constructor it does guarantee the original becomes empty. – François Andrieux Sep 25 '22 at 11:24
  • [Is a moved-from vector always empty?](https://stackoverflow.com/questions/17730689/is-a-moved-from-vector-always-empty) for more details. Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO posts for this. – Jason Sep 25 '22 at 11:24

0 Answers0