Move semantics should be used when you no longer need the original object and want to transfer ownership of its resources to another object. This is often the case when:
Example 1: You are returning a local object from a function:
Resource CreateResource() {
Resource Temp;
// ...
return Temp;
}
Here, Temp
is a local object that will be destroyed when the function returns. By using move semantics, we can efficiently transfer its resources to the object being returned.
Example 2: You are assigning from a temporary object:
Resource A;
A = Resource();
The temporary Resource()
will be destroyed after the assignment. Moving from it is more efficient than copying.
Example 3: You are passing an object to a function that will take ownership of it:
void TakeOwnership(Resource R) {
// ...
}
Resource A;
TakeOwnership(std::move(A));
By moving A
into the function, we efficiently transfer ownership of its resources to R
.
In general, use move semantics when you want to optimize the transfer of resources and don't need the original object anymore.
Answers to questions are automatically generated and may not have been reviewed.
Learn how we can improve the performance of our types using move constructors, move assignment operators and std::move()