1、函数式编程如std::bind、std::thread传参数等使用时,是对参数直接拷贝而不是引用

如:

#include

#include

void f(int& n1, int& n2, const int& n3)

{

std::cout << "In function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl;

++n1; // 增加存储于函数对象的 n1 副本

++n2; // 增加 main() 的 n2

//++n3; // 编译错误

std::cout << "In function end: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl;

}

int main()

{

int n1 = 1, n2 = 1, n3 = 1;

std::cout << "Before function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl;

std::function bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));

bound_f();

std::cout << "After function: n1[" << n1 << "] n2[" << n2 << "] n3[" << n3 << "]" << std::endl;

}

结果:

Before function: n1[1] n2[1] n3[1]

In function: n1[1] n2[1] n3[1]

In function end: n1[2] n2[2] n3[1]

After function: n1[1] n2[2] n3[1]

n1是普通值传递;n2是引用传递;n3是const引用传递

 

 

参考:https://blog.csdn.net/lmb1612977696/article/details/81543802

文章来源

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。