std::ref
and std::cref
are utility functions provided by the <functional>
header that enable passing references to objects when using std::bind
. These functions are particularly useful to avoid copying objects when binding them to a function.
Here's an example demonstrating how to use std::ref
with std::bind
:
#include <functional>
#include <iostream>
void SetValue(int& value, int newValue) {
value = newValue; }
int main() {
int value = 10;
auto SetValue10 = std::bind(
SetValue, std::ref(value), 10);
auto SetValue20 = std::bind(
SetValue, std::ref(value), 20);
SetValue10();
std::cout << "Value after SetValue10: "
<< value << '\n';
SetValue20();
std::cout << "Value after SetValue20: "
<< value << '\n';
}
Value after SetValue10: 10
Value after SetValue20: 20
In this example:
SetValue
function takes a reference to an int
and a new value, updating the int
with the new value.SetValue10
and SetValue20
, using std::bind
. Here, std::ref(value)
ensures that SetValue
receives a reference to value
rather than a copy.SetValue10
and SetValue20
are called, they modify the original value
variable.Similarly, std::cref
can be used to bind a const reference to an object, which is useful when you want to bind a reference to a const object or a temporary object that should not be modified.
Here's an example demonstrating std::cref
:
#include <functional>
#include <iostream>
#include <string>
void PrintString(const std::string& str) {
std::cout << str << '\n'; }
int main() {
std::string tempStr = "Hello";
auto Print = std::bind(
PrintString, std::cref(tempStr));
Print();
}
Hello
In this example:
PrintString
function takes a const reference to a std::string
and prints it.std::string
object tempStr
with the value "Hello"
.std::cref(tempStr)
to bind a const reference to tempStr
.Print
functor, when called, passes this const reference to PrintString
, which prints the string.By using std::cref
, we ensure that the std::string
object is not copied and is passed as a const reference to the bound function.
In summary, std::ref
and std::cref
are valuable tools for binding references to functions with std::bind
, allowing you to avoid unnecessary object copying and maintain the integrity of the original objects.
Answers to questions are automatically generated and may not have been reviewed.
This lesson covers function binding and partial application using std::bind()
, std::bind_front()
, std::bind_back()
and std::placeholders
.