Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why std::move behaves like std::copy? [duplicate]

Consider the following piece of code -

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{

    std::vector<int> d {100, 200, 300};
    std::vector<int> l {1, 2, 3, 4, 5};

    std::move(d.begin(), d.end(), std::inserter(l, l.begin()));

    for (int n : l) std::cout << n << ' ';
    std::cout << '\n';
    for (int n : d) std::cout << n << ' ';
    std::cout << '\n\n';


    for (int &n : d) n +=5;

    for (int n : l) std::cout << n << ' ';
    std::cout << '\n';
    for (int n : d) std::cout << n << ' ';
    std::cout << '\n';
}

Here the original std::vector l was inserted with contents of std::vector d after the move operation. I know that all standard library objects that have been moved from are placed in a valid but unspecified state, however, I was curious to move further and inspect the values. The value of std::vector d still remained same after the move operation which could be justified as if both are referring to same data location? Again, when I tried to modify those values, the change is not reflected back in the new std::vector l container.

Here's the output -

100 200 300 1 2 3 4 5 
100 200 300 

100 200 300 1 2 3 4 5 
105 205 305

It seems the values are copied from source container to destination container and the source container gets to keep originals. Doesn't this sound like a std::copy operation?

like image 699
Abhinav Gauniyal Avatar asked Feb 22 '26 23:02

Abhinav Gauniyal


1 Answers

For plain old data, moving and copying are identical. There's no way to move ordinary data other than by copying. Things are different if, for example, you have ownership of some other object that can be transferred without copying it (like std::string or std::shared_ptr has). But for int, that doesn't apply.

like image 118
David Schwartz Avatar answered Feb 24 '26 12:02

David Schwartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!