美文网首页
stl std::ref std::cref

stl std::ref std::cref

作者: 离水的鱼5746 | 来源:发表于2019-04-03 09:06 被阅读0次

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

  • ref与cref的区别就是const,前者是T&,后者是const T&。
  • return std::reference_wrapper

template

#include <functional>
#include <iostream>

void f(int& n1, int& n2, const 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()> 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';
}

result

Before function: 10 11 12
In function: 1 11 12
After function: 10 12 12

reference_wrapper的作用

//伪代码
typedef std::function<void> Functor;
vector<Functor> functors_;
package_task<void()> task(()[]{...});
future f=task.get_future();
//functors_.emplace_back(std::move(task)); //error:提示调用了delete的copy Constructor
functors_.emplace_back(std::ref(task));

task重载了operator()是可以压入functors_的,但是容器内的元素都要符合可copy Constructor的要求。《STL源码剖析》里第2章有所提及。
std::reference_wrapper是可复制构造(CopyConstructible)且可复制赋值(CopyAssignable)的引用包装器。所以经过包装后task可传入functors_。

相关文章

  • stl std::ref std::cref

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

  • 再说智能指针

    一 STL的智能指针及使用 STL中智能指针有std::shared_ptr std::weak_ptr std:...

  • bind

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

  • std::ref

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

  • std::ref

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

  • 转载--std::ref应用

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

  • 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_...

  • stl std::future

    https://zh.cppreference.com/w/cpp/thread/future std::futu...

网友评论

      本文标题:stl std::ref std::cref

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