1

While trying to learn std::move and rvalue reference , i just came across the following:

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> vecNumbers;
    vecNumbers.push_back(10);
    vecNumbers.push_back(20);

    foo(std::move(vecNumbers));

    std::cout<<"After Move \n";
    std::cout<<"size:"<<vecNumbers.size()<<"\n";

    return 0;
}

void foo(  std::vector<int> &&value)
{
    std::cout<<"size in Function:"<<value.size()<<"\n";
}

The Output

size in Function:2
After Move
size:2

I was expecting the size to be 0 after calling move on vector but here it only moved as reference. Could someone please explain what is happening here.

2
  • 1
    Did you move (stole content of ) value inside foo? No, so why you assume that this vector should have size 0 ? move only cast to Rvalue ref. Commented Sep 17, 2019 at 6:05
  • 2
    As Scott Meyers likes to say: std::move does not move (and std::forward does not forward). Commented Sep 17, 2019 at 6:45

2 Answers 2

5

std::move only casts to Rvalue reference.

foo takes Rvalue ref to vector<int>. By move(vecNumbers) you get vector<int>&&. Inside foo you just access vecNumbers which is defined in main. You didn't do any action which changed the content of this vector.

If you really want to move (steal) content of vecNumbers you have to call either move constructor or move assignment operator. Inside foo you could do this in this way:

void foo(  std::vector<int>&& value)
{
    std::vector<int> v1{std::move(value)}; // invoke move ctor which steals content of value
    std::cout<<"size in Function:"<<value.size()<<"\n";
}

or you can change signature of foo to be:

void foo(std::vector<int> value) {

}

then when you call

foo(std::move(vecNumbers))

move constructor of vector<T> is called which moves vecNumbers to value inside foo.

Sign up to request clarification or add additional context in comments.

Comments

3

Your assumption about move is wrong:

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object.

In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.

This doesn't mean the size of vector should become zero with your code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.