Advanced11 min readLesson 44 of 50
lvalues and rvalues
An lvalue has a name and a persistent memory address. An rvalue is a temporary value with no address.
int x = 42; // x is lvalue; 42 is rvalue
string s = "hi"; // s is lvalue; "hi" is rvalue
string t = s; // copy: expensive for large strings
std::move and Move Constructor
std::move transfers ownership of resources instead of copying them — no memory allocation, much faster for large objects:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Buffer {
public:
vector<int> data;
Buffer(int size) : data(size, 0) {
cout << "Constructed, size=" << data.size() << endl;
}
// Move constructor
Buffer(Buffer&& other) noexcept : data(move(other.data)) {
cout << "Moved!" << endl;
}
};
int main() {
Buffer b1(1000000);
Buffer b2(move(b1)); // move, not copy
cout << "b1 size: " << b1.data.size() << endl; // 0 (stolen)
cout << "b2 size: " << b2.data.size() << endl; // 1000000
return 0;
}
Output:
Constructed, size=1000000
Moved!
b1 size: 0
b2 size: 1000000
Rvalue References
void process(string&& s) { // rvalue reference parameter
cout << "Moving: " << s << endl;
}
process("temporary"); // OK — rvalue
string name = "Alice";
process(move(name)); // cast lvalue to rvalue
Rule of Five: If you define a destructor, copy constructor, or copy assignment, also define move constructor and move assignment operator.
Exercise
Create a vector of 5 strings. Use std::move to move (not copy) one string into a new variable. Verify the original is empty after the move.
Show Solution
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> words = {"alpha","beta","gamma","delta","epsilon"};
string moved = move(words[2]);
cout << "Moved: " << moved << endl; // gamma
cout << "Original: " << words[2] << endl; // (empty)
return 0;
}
Quiz
What does std::move(x) actually do?
- A) Copies x to a new location
- B) Casts x to an rvalue reference, enabling the move constructor
- C> Deletes x
- D) Swaps x with another variable
Answer
B) std::move is just a cast — it enables the move constructor/assignment to steal resources.
Summary
- Move semantics transfer resource ownership instead of copying.
T&& is an rvalue reference; std::move() casts to one.- Move constructors and move assignment operators avoid expensive deep copies.
- Follow the Rule of Five when managing resources.