rvalue references
- C++ course
- Intermediate
- Lesson 100/116
- 5 min
Learn the rvalue reference (&&) concept.
rvalue references (&&)
An rvalue reference (T&&) binds to temporary values. While a normal reference (T&) binds to named variables, T&& binds only to temporary objects.
Example: void show(std::string&& s); can only be called with temporary strings: show("Hello"); works but std::string x = "Hello"; show(x); gives a compile error. This is because x is a named variable (lvalue) while "Hello" is a temporary (rvalue) string. rvalue references prevent unnecessary copies and enable move operations.
lvalue versus rvalue
In C++ every expression is either an lvalue (has a name, has an address) or an rvalue (temporary, no addressable storage).
Example: in int x = 5; the x is an lvalue and 5 is an rvalue. The expression x + 1 is also an rvalue because its result has no address. An rvalue reference (int&&) binds only to rvalues: int&& r = 5; is valid but int&& r = x; is an error. This distinction lets the compiler decide whether to copy or move.
Practice Write an rvalue reference function
Define a function named printValue. Its parameter is std::string&& s (rvalue reference). Its body is std::cout << s;. In main call printValue("Hello");.
Starter code
#include <iostream>
#include <string>
// Define the printValue function
int main() {
// Call the printValue function
return 0;
}Sample solution
#include <iostream>
#include <string>
void printValue(std::string&& s) {
std::cout << s;
}
int main() {
printValue("Hello");
return 0;
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What can std::string&& bind to?
void show(std::string&& s);
show(______);- A named variable (lvalue)
- A file
- A temporary value (rvalue) Correct answer
- A pointer
Explanation: An rvalue reference binds to temporary values.
2 rvalue reference parameter
void show(std::string____ s) { std::cout << s; }
void show(std::string&& s) { std::cout << s; }
Explanation: && is the rvalue reference operator.
3 Match each expression to its type
| Term | Meaning |
|---|---|
std::string&& |
rvalue reference |
std::string& |
lvalue reference |
"Hello" |
rvalue |
x (variable) |
lvalue |