Welcome to this comprehensive guide on std::ref and std::cref in C++! These two little helpers are powerful tools that can make your code more efficient and easier to work with. Let's dive in and learn together! š
std::ref and std::cref? šIn C++, std::ref and std::cref are functions from the <functional> library that create "reference wrappers". These wrappers enable you to pass references as arguments to functions that expect values.
std::ref šstd::ref creates a reference wrapper around a variable. It returns a reference to the original variable, which can be passed to functions that expect values.
#include <iostream>
#include <functional>
int main() {
int num = 42;
std::cout << "Number: " << num << '\n';
std::reference_wrapper<int> num_ref = std::ref(num);
std::cout << "Reference Wrapped Number: " << num_ref << '\n';
std::cout << "Changing the reference wrapped number:\n";
num_ref = 99;
std::cout << "Number: " << num << '\n'; // Number: 42 (original number remains unchanged)
std::cout << "Reference Wrapped Number: " << num_ref << '\n'; // Reference Wrapped Number: 99
return 0;
}std::cref šstd::cref creates a reference wrapper for const values or references. It is particularly useful when you want to pass const references to functions that require non-const arguments, which can be the case with some standard library functions.
#include <iostream>
#include <functional>
int main() {
const int num = 42;
std::cout << "Number: " << num << '\n';
const std::reference_wrapper<const int> num_cref = std::cref(num);
std::cout << "Reference Wrapped Const Number: " << num_cref << '\n';
std::cout << "Changing the reference wrapped number will cause a compile error.\n";
return 0;
}std::ref and std::cref? š”std::cref useful when you want to pass a const reference to a function that requires a non-const argument? šWhy is `std::cref` useful when you want to pass a const reference to a function that requires a non-const argument?
We've explored std::ref and std::cref in this guide, two handy tools in C++ that let you work with references in a more flexible way. Practice using these functions to make your code more efficient and expressive! š”