[转]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引用)

 

原文链接: https://www.cnblogs.com/yi-mu-xi/p/9896461.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/404017

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月23日 上午9:41
下一篇 2023年4月23日 上午9:42

相关推荐