https://zh.cppreference.com/w/cpp/utility/functional/ref
- ref与cref的区别就是const,前者是T&,后者是const T&。
- return std::reference_wrapper
template
#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));
n1 = 10;
n2 = 11;
n3 = 12;
std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
bound_f();
std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
result
Before function: 10 11 12
In function: 1 11 12
After function: 10 12 12
reference_wrapper的作用
//伪代码
typedef std::function<void> Functor;
vector<Functor> functors_;
package_task<void()> task(()[]{...});
future f=task.get_future();
//functors_.emplace_back(std::move(task)); //error:提示调用了delete的copy Constructor
functors_.emplace_back(std::ref(task));
task重载了operator()是可以压入functors_的,但是容器内的元素都要符合可copy Constructor的要求。《STL源码剖析》里第2章有所提及。
std::reference_wrapper是可复制构造(CopyConstructible)且可复制赋值(CopyAssignable)的引用包装器。所以经过包装后task可传入functors_。
网友评论