[转]c++11中 std::ref() 和 引用

使用std::ref可以在模板传参的时候传入引用,否则无法传递

&是类型说明符, std::ref 是一个函数,返回 std::reference_wrapper(类似于指针)

用std::ref 是考虑到c++11中的函数式编程,如 std::bind.

例子:

 1 #include <iostream>
 2 #include <functional>
 3  
 4 void foo(int& a) {
 5     ++a;
 6 }
 7  
 8 void foo2(const int& a){
 9     sdt::cout<<"a="<<a<<"\n";
10 }
11 
12 
13 void test_function(std::function<void(void)> fun) {
14     fun();
15 }
16  
17 int main() {
18     int a = 1;
19  
20     std::cout << "a = " << a << "\n";
21     test_function(std::bind(foo, a));
22     std::cout << "a = " << a << "\n";
23     test_function(std::bind(foo, std::ref(a)));
24     std::cout << "a = " << a << "\n";
25     test_function(std::bind(foo2,std::cref(a)));
26     std::cout<<"a =" <<a<<"\n";
27  
28     return 0;
29 }

 

输出:

a=1

a=1(因为std::bind将参数拷贝了,不对参数直接操作。而foo改变的是拷贝,不影响a)

a=2(若要使用引用来改变原来参数,就用std::ref() )

a=2 (std::cref() 用于const引用)

 

posted @ 2018-11-02 15:21  yimuxi  阅读(10621)  评论(0编辑  收藏  举报