Pages

std::move()

We have seen how we can use Rvalue reference to improve performance. Given Rvalue reference, we can overload functions to take adavantage of the fact that we know that the passed variable is just a temporary.

It would be a pity if we couldn't be able to use such a mechanism even on lvalue, when we are willing to take the responsibility of this act. After all C++ is known to let the programmer doing whatever he wants, for the good and for the bad. And actually we could use std::move() for this.

Recalling the code we used in the previous post, say we have an instance of Something, but we don't care anymore of it, we could treat it as it was a temporary. We say this to the compiler using std::move():

Something s5("hello");

Something s6 = std::move(s5); // 1.
s5 = std::move(s6); // 2.

1. Here we are saying to the compiler that we want to create a Something object from s5, and that it could call the ctor for Rvalue reference for doing it. We are aware of the consequences, or at least we should.
2. Naturally, we could do the same also for calling the assignment operator overloaded for Rvalue reference. Same caveat, the compiler trusts us, we should have designed the function correctly and we should accept the result of what is going on.

No comments:

Post a Comment