[modern c++] 函数式编程与 std::ref

参考:

std::ref, std::cref - cppreference.comicon-default.png?t=N7T8https://en.cppreference.com/w/cpp/utility/functional/ref

正文:

如果不涉及函数式编程,那么基本上不需要使用到 std::ref , 这个功能式是用来解决函数式编程时入参只能进行值传递的问题的,不过如果使用指针则同样不需要 std::ref,如果不用指针则大概率会需要。

#include <functional>
#include <iostream>
 
void f(int& n1, int& n2, const int& n3)
{
    std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    ++n1; // increments the copy of n1 stored in the function object
    ++n2; // increments the main()'s n2
    // ++n3; // compile error
}
 
int main()
{
    int n1 = 1, n2 = 2, n3 = 3;
/*
std::bind 的第二个参数以后都是传递给第一个参数的入参,这里的n1就是传值,那么f函数里的第一个参数就是值传递,第二个参数使用了 std::ref 包裹,那么就进行了引用传递,那么在 f里面对第二个参数的修改会影响外部函数的局部变量n2
*/
    std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
    n1 = 10;
    n2 = 11;
    n3 = 12;
    std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
    bound_f();
    std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值