stl std::ref std::cref

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_。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容