std::ref

作者: cx7 | 来源:发表于2019-03-14 20:54 被阅读0次

C++11引入了std::ref 为了解决函数式编程的参数是值拷贝的情况

这几个例子的情况各不相同
int a = 5;

auto fun = [](int &a){ //引用
    a++;
};

std::thread(fun,  a); //值拷贝 

std::bind(fun, a); // 值拷贝

以上的例子中 除了直接调用lambda 其余涉及到函数式编程的例子 参数都是值拷贝
std::ref正是应用在这个情况 将上述的式子改为

int a = 5;

auto fun = [](int &a){ //引用
    a++;
};

std::thread(fun,  std::ref(a)); //引用

std::bind(fun, std::ref(a)); //引用

假如异步编程遇到需要引用参数 获取结果值 就需要使用这种方式

相关文章

  • std::ref

    C++11引入了std::ref 为了解决函数式编程的参数是值拷贝的情况 以上的例子中 除了直接调用lambda ...

  • std::ref

    原文:https://murphypei.github.io/blog/2019/04/cpp-std-ref[h...

  • bind

    std::bind(&X::f, ref(x), std::placeholders::_1)(i); /...

  • stl std::ref std::cref

    https://zh.cppreference.com/w/cpp/utility/functional/ref ...

  • C++ concurrency in action: 1~4 章

    1 概述 2 管理线程: thread/join/detach/RAAI/std::ref/std::bind/m...

  • C++ concurrency in action: Key p

    1 概述 2 管理线程: thread/join/detach/RAAI/std::ref/std::bind/m...

  • std::ref()和&

    引言 最近看到一个多线程代码如下: 其中创建线程的部分使用了std::thread t1(accumulator_...

  • 转载--std::ref应用

    在std::promise范例中,使用了std::ref将future对象传递给引用参数类型的任务函数。 std:...

  • C++11为什么需要std::ref/reference_wra

    在std::promise范例中,使用了std::ref将future对象传递给引用参数类型的任务函数。 如果直接...

  • C++中隐式类型转换

    1 operator隐式类型转换 1.1 std::ref源码中reference_wrapper隐式类型转换 在...

网友评论

    本文标题:std::ref

    本文链接:https://www.haomeiwen.com/subject/urkhmqtx.html