码迷,mamicode.com
首页 > 编程语言 > 详细

c++ std::bind及std::ref的使用

时间:2020-06-26 12:43:40      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:cti   ios   iostream   bind   fun   class   cout   wrap   mil   

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 << "\tb:" << b << "\tc:" << c << std::endl;
    return 0;
}

以上程序的运行结果为:
a:1     b:2     c:1
 
由此可以得到以下结论:
a    std::bind总是使用值拷贝的形式传参,哪怕函数声明为引用
b    std::bind可以使用std::ref来传引用
c    std::bind虽然使用了std::ref传递了引用,如果函数本身只接受值类型参数,传递的仍然是值而不是引用。

c++ std::bind及std::ref的使用

标签:cti   ios   iostream   bind   fun   class   cout   wrap   mil   

原文地址:https://www.cnblogs.com/tongyishu/p/13194138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!