Perfect forwarding is a technique in C++ that allows you to forward arguments to a function while preserving their value category (lvalue or rvalue). This is particularly useful in template functions where you want to accept a wide variety of argument types without unnecessary copying.
The key to perfect forwarding is the use of the std::forward
function which helps to ensure that if you receive an rvalue, it gets forwarded as an rvalue, and if you receive an lvalue, it gets forwarded as an lvalue.
Here is an example demonstrating perfect forwarding and std::forward
:
#include <iostream>
#include <utility>
template <typename T>
void process(T&& arg) {
// Forward the argument to another function
handle(std::forward<T>(arg));
}
void handle(int& i) {
std::cout << "Lvalue reference: " << i << std::endl;
}
void handle(int&& i) {
std::cout << "Rvalue reference: " << i << std::endl;
}
int main() {
int x = 10;
process(x); // Calls handle(int&) - lvalue
process(20); // Calls handle(int&&) - rvalue
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?