CPP11中std::forward的唯一作用是把lvalue转为原来的rvalue

#include <iostream>
#include <memory>

/*
Title: std::forward的唯一作用是把lvalue转为原来的rvalue.
Author: kagula
Date: 2021-1-19
Motivation:
   网上对std::forward的功能过度解释, 就一句话 "因为有名字就是lvalue, 为了让这个lvalue类型变回rvalue, 只能使用std::forward.".
我用下面的示例说明std::forward的作用.
Test Environment:
  Visual Studio Community 2019
Glossary:
rvalue 右值类型
lvalue 左值类型
*/

struct A {
    A(int&& n) { std::cout << "rvalue overload, n=" << n << "\n"; }
    A(int& n) { std::cout << "lvalue overload, n=" << n << "\n"; }
};

template<class T, class U>
std::unique_ptr<T> make_unique_with_std_forward(U&& u)
{
    return std::unique_ptr<T>(new T(std::forward<U>(u)));
}

template<class T, class U>
std::unique_ptr<T> make_unique_without_std_forward(U&& u)
{
    return std::unique_ptr<T>(new T(u));
}

int main()
{
    {
        auto p1 = make_unique_with_std_forward<A>(2); // rvalue
        
        int i = 1; 
        auto p2 = make_unique_with_std_forward<A>(i); // lvalue
    }

    {
        std::cout << "Without std::forward always print out lvalue. \n";
        auto p1 = make_unique_without_std_forward<A>(2); // lvalue
        
        int i = 1; 
        auto p2 = make_unique_without_std_forward<A>(i); // lvalue
    }
}

猜你喜欢

转载自blog.csdn.net/lee353086/article/details/112811602