std::ref

内容分享3周前发布
0 0 0

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

C++11 中引入 std::ref 用于取某个变量的引用,这个引入是为了解决一些传参问题。

我们知道 C++ 中本来就有引用的存在,为何 C++11 中还要引入一个 std::ref 了?主要是思考函数式编程(如 std::bind)在使用时,是对参数直接拷贝,而不是引用。下面通过例子说明

示例1:

#include <functional>
#include <iostream>

void f(int& n1, int& n2, const int& n3)
{
    std::cout << "In function: " << n1 <<     << n2 <<     << n3 <<  
 ;
    ++n1; // increments the copy of n1 stored in the function object
    ++n2; // increments the main() s n2
    // ++n3; // compile error
}

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 <<  
 ;
    bound_f();
    std::cout << "After function: " << n1 <<     << n2 <<     << n3 <<  
 ;
}

输出:

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

上述代码在执行 std::bind 后,在函数 f()n1 的值依旧是 1,n2n3 改成了修改的值,说明 std::bind 使用的是参数的拷贝而不是引用,因此必须显示利用 std::ref 来进行引用绑定。具体为什么 std::bind 不使用引用,可能的确 有一些需求,使得 C++11 的设计者认为默认应该采用拷贝,如果使用者有需求,加上 std::ref 即可。

之所以std::bind默认是拷贝,由于std::function<void()> bound_f,这个函数变量可能不在当前作用域下执行,如果在其他作用域,那么当前作用域退出时,n1、n2、n3就会被释放,bound_f再次调用 f 函数时,如果 f 操作的还是原来的n1、n2、n3很可能出现内存错误,所以默认是拷贝;当改为 std::ref 时,必须人为确认使用引用没有问题,才能这么写

示例2:

#include<thread>
#include<iostream>
#include<string>

void threadFunc(std::string &str, int a)
{
 str = "change by threadFunc";
 a = 13;
}

int main()
{
 std::string str("main");
 int a = 9;
 std::thread th(threadFunc, std::ref(str), a);

 th.join();

 std::cout<<"str = " << str << std::endl;
 std::cout<<"a = " << a << std::endl;

 return 0;
}

输出:

str = change by threadFunc
a = 9

可以看到,和 std::bind 类似,多线程的 std::thread 也是必须显式通过 std::ref 来绑定引用进行传参,否则,形参的引用声明是无效的。

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
none
暂无评论...