Reputation: 41
I'm trying to understand how std::move with a simple example (below). Basically I'm trying to move to contents of p1 to p2, so p1 is empty after that, which doesn't happen though.
I guess I'm not using std::move properly. I would appreciate a lot if anybody could explain that to me.
#include <iostream>
#include <utility>
int main()
{
int * p1 = new int[10];
for(int i = 0; i < 10; ++i)
p1[i]=i;
// moving contents of p1 to p2
int * p2 = std::move(p1);
// I was expeting p1 now to be empty but it's not...
if(p1 != NULL)
std::cout << "I'M NOT EMPTY\n";
// prints I'M NOT EMPTY
}
Upvotes: 2
Views: 670
Reputation: 10137
Unfortunately, std::move
doesn't do what people new to C++11 often expect. It is defined by the C++ standard simply as a static_cast
, so on its own it doesn't actually modify the object it is given. There is often an expectation that std::move
will somehow clear or zero out the object being moved from, but as explained here, that's not at all what the C++ standard requires.
Also, riv's answer is only partially correct. The guarantee he talks about is not really to do with std::move
, it is more related to rvalue references and the guarantee is typically discussed in conjunction with move constructors and move assignment. If you want more background on std::move
, rvalues, etc., I highly recommend Thomas Becker's discussion which is one of the internet's most referenced sites on the subject.
Upvotes: 1
Reputation: 785
Maybe this
Why does moving a pointer variable not set it to null? can clarify what´s going on in your code. As riv pointed out, there is no reason to std::move assign NULL to your pointer.
This reference http://en.cppreference.com/w/cpp/utility/move has good examples of undefined behaviors when using std::move.
Upvotes: 1
Reputation: 7324
The move function is not guaranteed to clear the contents of the source object. It is, however, guaranteed to be left in such a state that you can safely destroy it or assign a new value to it.
Upvotes: 2