zoukankan      html  css  js  c++  java
  • c++ std::bind及std::ref的使用

    std::bind 的功能是将一个函数和它的参数预先绑定在一起,变成一个无参函数。

    std::bind 总是拷贝其参数,但是调用者可以使用std::ref来实现传递引用给std::bind。

    std::ref 返回一个 reference_wrapper 类型的变量,关于 std::ref 及 reference_wrapper 的具体实现可以参照 c++ <functional> 文件。

    一个例子说明std::ref的使用方法:

    #include <iostream>
    #include <functional>
    
    void test_fun(int& a, int& b, int c) {
        a++;
        b++;
        c++;
    }
    
    int main() {
        int a = 1, b = 1, c = 1;
        auto fun = std::bind(test_fun, a, std::ref(b), std::ref(c));
        fun();
        std::cout << "a:" << a << "	b:" << b << "	c:" << c << std::endl;
        return 0;
    }

    以上程序的运行结果为:
    a:1     b:2     c:1
     
    由此可以得到以下结论:
    a    std::bind总是使用值拷贝的形式传参,哪怕函数声明为引用
    b    std::bind可以使用std::ref来传引用
    c    std::bind虽然使用了std::ref传递了引用,如果函数本身只接受值类型参数,传递的仍然是值而不是引用。
  • 相关阅读:
    jQuery学习笔记----入门
    软件工程(第二周)
    软件工程(第一周)
    memcached 学习进修
    iis设置http重置到https
    apk的api级别不要低于26
    DDD 学习记录
    net core 随笔
    vs2017 无法提交到tfs的 git存储库
    nopcommerce 4.1 core 学习 增加商城配置属性
  • 原文地址:https://www.cnblogs.com/tongyishu/p/13194138.html
Copyright © 2011-2022 走看看