Loading

C++ bind注意事项(传引用参数的时候)

默认情况下,bind的那些不是占位符的参数被拷贝到bind返回的可调用对象中。

当需要把对象传到bind中的参数中时,需要使用ref或者cref。

例如:

 1 #include<iostream>
 2 #include<functional>
 3 
 4 using namespace std;
 5 using namespace placeholders;
 6 
 7 void alter(int &a,int b)
 8 {
 9     a = b;
10 }
11 
12 
13 int main()
14 {
15     int a = 5;
16     auto g = bind(alter, a, _1);      //此处bind中的参数a只是a的一个拷贝,而不是a的引用
17     g(9);                           
18     cout << a << endl;                //所以此处a仍为5
19 
20     auto f = bind(alter,ref(a), _1);  //使用ref可以将a的引用传递给bind
21     f(9);
22     cout << a << endl;                //所以此处a变成了9
23 
24     return 0;
25 }

 

posted @ 2018-07-06 10:02  拾月凄辰  阅读(454)  评论(0编辑  收藏  举报