Module 12: ReferencesIntermediate45 min read
Lvalue & Rvalue References, Const References & Pointers vs References
Master C++ references, why references cannot be null or reseated, const T& optimization, and C++11 rvalue references (T&&) for move semantics.
Key Takeaways & Core Concepts
- is an alias for an existing object. Unlike pointers, references must be initialized at declaration, cannot be null, and cannot be reseated.
const T&can bind to both lvalues and temporary rvalues, extending a temporary's lifetime to the reference's scope!- binds exclusively to temporary/expiring values, enabling move constructors and move assignment to steal heap buffers in O(1) instead of deep-copying.
- | Yes (
nullptr) | No |
1. Lvalue References (`T&`) & Const References (`const T&`)
A reference is an alias for an existing object. Unlike pointers, references must be initialized at declaration, cannot be null, and cannot be reseated.
const T&can bind to both lvalues and temporary rvalues, extending a temporary's lifetime to the reference's scope!
1. Pass-by-Reference Swap & Rvalue Reference
1#include <iostream>
2
3void swapInts(int& a, int& b) {
4 int tmp = a; a = b; b = tmp;
5}
6
7int main() {
8 int x = 10, y = 20;
9 swapInts(x, y);
10 int&& tempSum = x + y;
11 std::cout << "x=" << x << ", y=" << y << ", tempSum=" << tempSum << "\n";
12 return 0;
13}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
13 lines
Note: `swapInts` mutates `x` and `y` directly; `int&&` binds to the temporary `x + y`.
2. Rvalue References (`T&&`, C++11) & Move Semantics
An rvalue reference binds exclusively to temporary/expiring values, enabling move constructors and move assignment to steal heap buffers in O(1) instead of deep-copying.
3. Pointers vs. References
| Feature | Pointer (T*) | Reference (T&) |
|---|---|---|
| Can be null? | Yes (nullptr) | No |
| Can be reseated? | Yes | No |
| Syntax | Requires * / -> | Direct object syntax |
| Arithmetic | Yes | No |
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)