温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c++中ref的作用是什么

发布时间:2023-05-05 16:17:09 来源:亿速云 阅读:129 作者:iii 栏目:开发技术

这篇文章主要讲解了“c++中ref的作用是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“c++中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 << '\n';
    ++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 << '\n';
    bound_f();
    std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
输出:

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

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

#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;
}

该程序创建一个线程 th,调用带有两个参数的 threadFunc 函数:一个是 std::string 对象 str 的引用,另一个是整数 a。函数 threadFunc 修改字符串 str 为 "change by threadFunc",但不修改整数 a。最后在主线程中输出 stra 的值。

输出:

str = change by threadFunc
a = 9

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

感谢各位的阅读,以上就是“c++中ref的作用是什么”的内容了,经过本文的学习后,相信大家对c++中ref的作用是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI