和&的区别在于:&是类型说明符,而std::ref,std::cref是函数,需要被包装的到对象的左值引用,或 std::reference_wrapper 的实例
std::ref 用于包装按引用传递的值。
std::cref 用于包装按const引用传递的值。
之所以会有std::ref,std::cref,主要是考虑c++11中的函数式编程,例如:std::bind(...)
std::bind调用时,传递的参数的拷贝,而不是引用
#include <functional>
#include <iostream>
void f(int& n1, int& n2, const int& n3)
{
std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
++n1; // 增加存储于函数对象的 n1 副本
++n2; // 增加 main() 的 n2
// ++n3; // 编译错误
}
int main()
{
int n1 = 1, n2 = 2, n3 = 3;
std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
bound_f();
std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
/*
Before function: 1 2 3
In function: 1 2 3
After function: 1 3 3
*/