ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c++11 为什么使用ref,和引用的区别

2022-09-16 18:33:54  阅读:236  来源: 互联网

标签:11 std cout int c++ 引用 include ref


std::ref只是尝试模拟引用传递,并不能真正变成引用,在非模板情况下,std::ref根本没法实现引用传递,只有模板自动推导类型时,ref能用包装类型reference_wrapper来代替原本会被识别的值类型,而reference_wrapper能隐式转换为被引用的值的引用类型。

std::ref主要是考虑函数式编程(如std::bind)在使用时,是对参数直接拷贝,而不是引用

其中代表的例子是thread
比如thread的方法传递引用的时候,必须外层用ref来进行引用传递,否则就是浅拷贝。

线程函数的参数按值移动或复制。如果引用参数需要传递给线程函数,它必须被包装(例如使用std :: ref或std :: cref)。

复制代码
#include <functional>
#include <iostream>
#include<cstring>
#include<string.h>
#include<memory>
#include<atomic>
#include<unordered_map>
#include<mutex>
#include <thread>
#include <string>
void method(int & a){ a += 5;}

using namespace std;
int main(){

    int a = 0;
    // each reference used by the threads would refer to the same object.
    thread th(method,ref(a));
    th.join();
    cout << a <<endl;
    /*
     *
I could compile your code successfully with MSVC2013. However, thread() works passing copies of its argument to the new thread. This means that if your code would compile on your compiler, each thread wourd run with its own copy of ht, so that at the end, main's a would be empty.
GCC doesn't compile with this weird message.
     */
    /*thread th2(method, a);  //浅拷贝
    th2.join();
    cout << a <<endl;*/
    return 0;
}
复制代码

 

复制代码
/** @file  bindRefT.cpp
*  @note   
*  @brief
*  @author 
*  @date   2019-8-8
*  @note   
*  @history
*  @warning
*/
#include <functional>
#include <iostream>
//std::ref主要是考虑函数式编程(如std::bind)在使用时,是对参数直接拷贝,而不是引用
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';
}
复制代码

 

标签:11,std,cout,int,c++,引用,include,ref
来源: https://www.cnblogs.com/lidabo/p/16700903.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有