std::ref 作用

#include <functional>
#include <iostream>

void f(int& n1, int& n2, 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(int &)> bound_f = std::bind(f, n1, std::ref(n2), std::placeholders::_1);
    n1 = 10;
    n2 = 11;
    n3 = 12;
    std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    bound_f(n3);
    std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}

std::ref 的使用:

1、在使用 bind 时对函数变量参数进行引用赋值,即参数是一个地址或引用,

使用ref,当初始化后,修改参数值,再次调用 bound_f 时参数使用新的值,n2==11 
如果不使用ref,如 n1,在bound_f初始化时,参数值已经固定无法修改。

2、对于占位符,并不需要考虑这个问题,因为本身就是引用,bind需要是因为,最被设计时使用的是值引用。
  一般是固定值。
 如果是可变,那么也不大需要使用 bind.

猜你喜欢

转载自blog.csdn.net/liuzhuchen/article/details/81349049
今日推荐