Move-Semantics
Move-Semantics, Before understanding move-semantics lets understand shallow-copy, deep-copy, lvalue, rvalue
“If” we have “pointer” in one class and we do shallow copy then it creates problem, as the destruction of one class object will delete other causing dangling pointer. Hence, deep copy is required which only copies the value not the pointer.
“lvalue” should be modifiable i.e. not “const”.An identifier is a modifiable lvalue if it refers to a memory location and if its type is arithmetic, structure, union, or pointer.
“rvalue” refers to data value that is stored at some address in memory. A r-value is an expression that can’t have a value assigned to it which means r-value can appear on right but not on left hand side of an assignment operator
below program works absolutely fine since lvalue is a reference to a memory address
#include<bits/stdc++.h>
using namespace std;
int &getvalue(){
static int i=10;
return i;
}
int main(){
int i = getvalue();
getvalue() = 5;
return 0;
}
lvalue “reference” can’t take value from rvalue, it should be lvalue, hence below program doesn’t work
int setvalue(int &i){
i=i*5;
return i;
}
int main(){
int i=10;
setvalue(i);
<!-- below one doesn't work, will throw compiler error -->
setvalue(10);
}
however if we make setvalue() parameter as const then it works fine.
int setvalue(const int &i){
i=i*5;
return i;
}
int main(){
int i=10;
setvalue(i);
<!-- below one works fine -->
setvalue(10);
}
one reason behind using const in function is also that, it accepts both temporary value & lvalues, as shown above.
Now, the questions is what’s the use of these? Basically we can detect what is temporary value or lvalue.
But wait, Is there a way to detect only rvalue. Yes, there is. Just use double “&&” in function parameter.
One more point, we use this “&” and “&&” to detect the parameter that is passed to it, so that we can deal accordingly, if its only lvalue we must make sure not to misutilize it. Howevere if its rvalue we can use it as we want.
int setvalue(int &&i){
i=i*5;
return i;
}
int main(){
int i=10;
<!-- below one works fine -->
setvalue(10);
<!-- below one doesn't works -->
setvalue(i);
}
Finally we’re ready for Move-Semantics Move semantics is about moving objects around the program. rvalue reference was introduced in c++ 11
Move Semantics is moving the objects across application, so what if the scenario is constructing a object in current stack frame and copying it to the function where it is need to used, (suppose here constructing the object in current stack frame is mandatory).
Copying object around is costlier, hence we can simply move the objects around with the rvalue reference instead of creating it.