lvalue, rvalue. Copy and Move Constructors
lvalue, rvalue
lvalue(locator value): Anything that can hold a address. Appear on the left-hand side of an assignment. rvalue(read value): temporary value that does not occupy a persistent memory location. Appears on the right-hand side of an assignment
int a = 10; // a is l value
// 10 is rvalue
int x = a+b; // x is l value
// a+b is rvalue
lvalue reference (&)
Reference to bind to lvalue. Usage: Pass large objects without copying.
int a = 10;
int &b = a; // lvalue reference
b = 11;
cout << a; // 11
Copy Constructor
Copy Ctr(Creates copy of object) is lvalue reference
using vi = vector <int>;
class A {
vi a;
void print() {
for (decltype(auto)i:a)
cout << i;
}
public:
A(vi& b):a(b) { // copy ctr (using lvalue ref). Created a copy
cout << "\nCopy ctr\n";
print();
}
};
int main() {
vi a = {1,2,3};
A obj(a); // Copy ctr called. Local copy remains present
cout << "\nAfter copy ctr in main()\n";
for(decltype(auto)i:a)
cout << i;
}
/*
$ ./a.out
Copy ctr
1 2 3
After copy ctr in main()
1 2 3
$
*/
rvalue reference (&&)
Reference that binds to an rvalue(temporary value). Usage: ?Move semantics (ie moving a temporary without copying it). ?Perfect forwarding in template functions.
领英推荐
int a = 10;
int &&b = 10; // rvalue reference
Move Constructor
Move Ctr(moves the object) is rvalue reference
using vi = vector <int>;
class A {
vi a;
void print() {
for (decltype(auto)i:a)
cout << i;
}
public:
//A(vi&& b):a(b) ///////// This will make copy. Not correct move ctr ///////////
A(vi&& b):a(move(b)) { // move ctr (using rvalue ref).
cout << "\nmove ctr\n";
print();
}
};
int main() {
vi a = {1,2,3};
A obj(a); // Copy ctr called. Local copy remains present
// move invokes a r value ref
A obj1(move(a)); // move(a) is equal to (int &&x = a)
cout << "\nAfter move ctr in main()\n";
for(decltype(auto)i:a)
cout << i;
}
/*
$ ./a.out
move ctr
1 2 3
After move ctr in main() //Value moved not availble in main
$
*/
XValue / Expiring?Value
(b+c) is called xvalue/temporary value which is ready to expire
a = b+c;
PRValue / Pure R?Value
Literal value is called pure R value
a = 42;
Conclusion
lvalue, rvalue provides base for copying and moving objects in C++, hence understanding l,r value reference is important.