#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_f
CPP11中std::forward的唯一作用是把lvalue转为原来的rvalue
最新推荐文章于 2024-01-24 18:12:08 发布
本文深入探讨C++11中的std::forward函数,其主要功能在于将lvalue精准地转换为原始的rvalue,这对于模板编程和高效资源管理至关重要。通过std::forward,可以保留变量的引用性质,从而实现更灵活和高效的类型传递。
摘要由CSDN通过智能技术生成