When to use move semantics over references or unique pointers?

Viewed 338

I am new to C++, and just learning about move semantics. So from what I understand, using the move constructor I can do something like

MyObj obj1;
MyObj obj2 = std:move(obj1);

And we have to define our own move constructor that cleans up obj1 etc.

It seems we can instead have obj2 be a reference to obj1 if we know that obj1 will not be destroyed before obj2 is done being used. But otherwise, can't we just use an unique_ptr instead? Such that we just create an unique pointer for obj1 and then pass this pointer instead of trying to move the object?

Is there some cases I am not considering?

1 Answers

From the example you provided I agree you could use a reference here or even a shared_ptr but it really depends on your use case.

However, move semantics are very handy in expressing a change of ownership. For example suppose obj1 is some resource (think database connection, a file you are writing too, etc). And now consider the following:

int func1() {
   MyObj obj1;
   // do something with obj1
   func2(std::move(obj1));
   // do some other stuff without obj1
   return 0;
}

in the third line of func1 we transfer the ownership of obj1 to func2. After this line, func1 no longer owns obj1 and should not use it whereas func2 can do whatever it needs to do with obj1.

This is especially useful for resources, like a file, where func1 could do something with the file and then have func2 do something else. By using std::move it's kind of like a contract that func1 won't modify this object anymore. This prevents func1 from potentially overwriting the work done by func2

Related