+ 5
Help me with std::move. Thank you :)
How does std::move work? I mean, I know it casts the argument to an rvalue reference but, it doesn't make sense in some cases, for me. For example see the following code: ...... int x=5; std::vector<int> arr; arr.push_back(std::move(x)); ...... Here, the vector is on the heap, and "x" is on the stack. How actually is it being moved from the stack to the heap? What I think is, the only way to do this is to actually copy the value of x to the location. If that's the way, then what's the use of using std::move() here? PS: This example is just for explanation of my doubt, otherwise it's better to copy an int rather than move it
7 Answers
+ 2
This is because a "move" will not happen in this case and it will degrade down to a copy.
+ 1
Rishi looks like you are confused here.
Consider "moving" as a swap operation. In case of heap allocated objects, you are just swaping the pointers pointing to the data on heap and the new pointer created that would be pushed to stack( which is valid but point to undefined object ), but for other cases it would be similar to a copy operation.
+ 1
Arsenic I think I get it. I don't know, but when I see it now, I feel like it's clear. Thank you :)
0
Arsenic right but, see the link that Martin Taylor has shared, it says opposite
0
Martin Taylor I saw that one but, the string is on the stack right? How does it "move" the item from stack to heap??? Or does it actually doing copy and setting the source to some other valid value?
0
Arsenic your explanation is clear for me in the following case:
.....
int a{9},b{5};
int temp{};
temp=std::move(a);
a=std::move(b);
b=std::move(temp);
.....
But consider a vector of integers. In this case, all the elements are in adjacent memory right? For example,
.....
std::vector<int> arr{1,2,3};
.....
In this case, if the address of 1 is 4000, the address of 2 should be 4008 and the address of 3 should be 4012(considering the size of int as 4 bytes) right? But, I can't understand how the following line works.
.....
std::vector<int> arr{1,2,3};
int a{5};
arr[2]=std::move(a);
.....
In this case, how is a "move" done??? Variable a is in stack somewhere, and arr[2] is in the heap. It merely just copies? but if so, then what's the use of std::move() here?
0
Rishi I don't know what's confusing here.
All you are doing is assigning an rvalue reference ( return value of std::move(a) ) to an lvalue, which is totally valid here and is similar to writting ( arr[2] = 5 )
Or am I missing something here ?