C++ ref与&

https://blog.csdn.net/ii0789789789/article/details/94899531,这个讲的很好

1.ref和&的例子

链接中讲的例子很好。

2.函数式编程

是对参数直接进行拷贝,而不是引用。

void f(int &a,int &b,int &c){
    cout<<"in function a = "<<a<<"  b = "<<b<<"  c = "<<c<<endl;
    a += 1;
    b += 10;
    c += 100;
}
 
int main(){
 
    int n1 = 1 ,n2 = 10,n3 = 100;
 
    function<void()> f1 = bind(f,n1,n2,ref(n3));
 
    f1();
    cout<<"out function a = "<<n1<<"  b = "<<n2<<"  c = "<<n3<<endl;
    f1();
    cout<<"out function a = "<<n1<<"  b = "<<n2<<"  c = "<<n3<<endl;
 
    return 0;
}

输出:
in function a = 1  b = 10  c = 100
out function a = 1  b = 10  c = 200
in function a = 2  b = 20  c = 200//迷惑,这里为什么变成了20????
out function a = 1  b = 10  c = 300

可以看到,在bind进行函数式编程的时候,对n3使用了ref,而其他两个参数没有使用,但是结果也很奇怪,这个可能要等我学习了函数式编程的时候才能明白具体是如何调用的吧。

ref会提供一个引用包装器reference_wrapper包装原始的值类型为引用类型,然后传递引用参数。

比如说在线程中:

void method(int & a){ a += 5;}
 
using namespace std;
int main(){
 
    int a = 0;
    thread th(method,ref(a));
    th.join();
    cout << a <<endl;
    //thread th2(method,a);  //去掉注释会编译出错
//error: no matching function for call to '__invoke(std::__tuple_element_t<0, std:
    //th2.join();
    cout << a <<endl;
    return 0;
}

输出:5 5

原文地址:https://www.cnblogs.com/BlueBlueSea/p/13892880.html