Sub topic 3
Rvalue references
Rvalue references
An rvalue is a value that is often temporary, such as the result of 2 + 3. An rvalue reference, written T&&, can bind to an rvalue of type T.
A named reference is an lvalue expression, even if its type is an rvalue reference. An lvalue is an expression that identifies an object.
Move semantics and std::move
Move semantics let an object transfer resources, such as a string’s stored text, instead of copying them. This can avoid extra work.
std::move marks an object as available to move from. It does not move anything by itself. A later operation, such as construction, may move from it. A moved-from standard library object remains valid, but its value is unspecified.
Overloading on reference types
Overloading means giving functions the same name but different parameter types. A function taking int& can handle a changing integer passed as an lvalue. One taking int&& can handle an rvalue.
Deducing reference types
Type deduction means letting the compiler work out a type. If n is an int:
auto copy = ncreates a separateint.auto& alias = nrefers ton.auto&& inferred = nalso refers ton.
A template is a pattern for code that works with different types. It can deduce types too.
Reference collapsing
When deduction combines reference types, reference collapsing chooses the result. Two rvalue references collapse to &&. Any combination containing & collapses to &.
Forwarding references
A forwarding reference is a deduced template parameter written T&&. It can accept either an lvalue or an rvalue. std::forward<T> passes it onward with the caller’s original value category. This is called perfect forwarding, though it does not work for every argument, such as a bare {...} list.
Reference wrappers
std::reference_wrapper is an object that holds a reference-like link. A container can store wrappers, even though it cannot store references directly. std::ref creates a wrapper. The referred-to object must outlive the wrapper.
Try it
Save this as main.cpp and compile it with a C++17 compiler.
#include <functional>
#include <iostream>
#include <string>
#include <utility>
void use(int& value) {
std::cout << "lvalue: " << value << '\n';
}
void use(int&& value) {
std::cout << "rvalue: " << value << '\n';
}
template<class T>
void relay(T&& value) {
use(std::forward<T>(value));
}
int main() {
std::string original = "hello";
std::string&& ref = std::move(original);
std::string result = std::move(ref);
std::cout << result << '\n';
int n = 2;
relay(n);
relay(2);
auto wrapped = std::ref(n);
++wrapped.get();
std::cout << n << '\n';
}The program prints hello, then lvalue: 2, rvalue: 2, and 3. The wrapper changes n, not a copy.
Exercise
Why does relay(n) call use(int&)?
Show answer
n is an lvalue. Deduction and reference collapsing make the forwarding reference an int&, and std::forward preserves that choice.