• 完美转发与底层原理剖析(引用折叠)


    万能引用与完美转发

    万能引用:即模板参数T&&,它既可以作为右值引用接收右值也可以作为左值引用接收左值

    完美转发:

    void Fun(int& x) { cout << "lvalue ref" << endl; }
    void Fun(int&& x) { cout << "rvalue ref" << endl; }
    void Fun(const int& x) { cout << "const lvalue ref" << endl; }
    void Fun(const int&& x) { cout << "const rvalue ref" << endl; }
    
    int main()
    {
    	int&& x1 = 10;
    	Fun(x1); // 输出结果为lvalue ref
    	const int&& x2 = 10;
    	Fun(x2); // 输出结果为const lvalue ref
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    输出结果都是左值,这是因为:当右值引用变量接收了一个右值后,它会开辟一块空间存放这个右值,对于自定义类型还会调用它的构造函数,因此可以说,该右值变量退化为一个左值变量

    为了解决这一问题,C++11提供了完美转发forward模板函数

    template  T&& forward (typename remove_reference::type& arg) noexcept;
    
    • 1
    void Fun(int& x) { cout << "lvalue ref" << endl; }
    void Fun(int&& x) { cout << "rvalue ref" << endl; }
    void Fun(const int& x) { cout << "const lvalue ref" << endl; }
    void Fun(const int&& x) { cout << "const rvalue ref" << endl; }
    
    int main()
    {
    	int&& x1 = 10;
    	Fun(forward(x1)); // 输出结果为rvalue ref
    	const int&& x2 = 10;
    	Fun(forward(x2)); // 输出结果为const rvalue ref
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    为了使一个函数既可以接受左值,又可以接受右值,C++11 之前的解决方案是将参数类型设为 const Type&。但是常左值引用限制了参数是常量,无法修改

    C++提出了万能引用+完美转发的解决方案:万能引用能接受左值和右值,保证参数可修改,而完美转发又能保证右值不会退化成左值。

    完美转发的底层原理

    // forward an lvalue as either an lvalue or an rvalue
    template 
    _NODISCARD constexpr _Ty&& forward(remove_reference_t<_Ty>& _Arg) noexcept 
    { 
        return static_cast<_Ty&&>(_Arg);
    }
    
    // forward an rvalue as an rvalue
    template 
    _NODISCARD constexpr _Ty&& forward(remove_reference_t<_Ty>&& _Arg) noexcept 
    { 
        static_assert(!is_lvalue_reference_v<_Ty>, "bad forward call");
        return static_cast<_Ty&&>(_Arg);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    完美转发的原理牵涉到两个部分:

    1. 引用折叠
    引用1引用2折叠结果
    &&&
    &&&&
    &&&&
    &&&&&&

    举个例子:如果实参的类型为T&,模板参数的类型为T&&,则混合起来就是T& &&,此类型会被编译器识别成T&

    如果任一引用为左值引用,则结果为左值引用。当且仅当两个都是右值引,结果为右值引用

    注意:编译器能够识别形如T& &&的引用,但是用户不可以这样写。

    1. 返回值中, 左值引用的值类型是左值,右值引用的值类型是右值。无论是forward也好,还是move也好,都是通过函数返回值来实现左值化和右值化的
  • 相关阅读:
    网络适配器设置步骤
    CompletableFuture详解-初遇者-很细
    做一个物联网温湿度传感器(一)SHT30传感器介绍
    ce从初阶到大牛(两台主机免密登录)
    StarRocks 技术内幕 | Join 查询优化
    Android学习笔记 61. 使用布局编辑器进行线性布局
    el-table自适应列宽实现
    Flutter网络请求和数据解析
    SpringBoot+Vue“咱村那些事”乡村基层信息采集系统
    Harmony 复杂图形自绘制
  • 原文地址:https://blog.csdn.net/Wyf_Fj/article/details/127137373