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


    万能引用与完美转发

    万能引用:即模板参数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也好,都是通过函数返回值来实现左值化和右值化的
  • 相关阅读:
    详解红黑树,图文并茂
    minio文件迁移
    生物素标记肽Biotin-εAhx-GLKLRFEFSKIKGEFLKTPEVRFRDIKLKDN
    精研科技融入汽车内饰 Laedana打造车内空间新生态
    一幅长文细学JavaScript(二)——一幅长文系列
    realEngine(UE4)实现开关门效果
    内网信息收集
    【UE5 刺客信条动态地面复刻】实现无界地面01:动态生成
    五分钟了解django、drf重写user表(详细又全面的一次记录)
    Day5:三指针描述一颗树
  • 原文地址:https://blog.csdn.net/Wyf_Fj/article/details/127137373