C++—完美转发
文章目录
1. std::forawrd
std::forward<T>(arg) 可以实现完美转发,即如果 arg 是一个右值引用,则转发之后结果仍是右值引用;反之,如果 arg 是一个左值引用,则转发之后结果仍是左值引用.
#include <iostream>
struct BigObject
{
char data[1 << 10];
};
void g(BigObject& o)
{
std::cout << "lvalue reference\n";
}
void g(BigObject&& o)
{
std::cout << "rvalue reference\n";
}
template <typename T>
void f(T&& arg)
{
g(std::forward<T>(arg));
}
int main()
{
BigObject o;
f(o);
f(BigObject());
}lvalue reference
rvalue reference2. 为什么需要完美转发?
- 在函数模板编程中,常有一种场景是使用模板参数去调用另一个函数(如,上例中
f去调用g),这时候如果只提供值传递版本会显得效率太低。 - 函数的参数一般会尽可能地设为引用类型,以避免对象拷贝带来的高昂开销.
- 为了使一个函数既可以接受左值,又可以接受右值,C++11 之前的解决方案是将参数类型设为
const Type&. 但这并不是很方便,如限制了参数是常量. - 如果函数
g既提供了左值引用版本和右值引用版本,则最好的情况是函数f可以根据参数类型去调用相应版本的g. 而完美转发正可以满足此要求.
3. 引用折叠规则
- 右值引用和右值引用叠加将得到右值引用;
- 右值引用和左值引用叠加将得到左值引用;
- 左值引用和左值引用叠加将得到左值引用.
template <typename T>
using TR = T&;
// v 的类型
TR<int> v; // int&
TR<int>& v; // int&
TR<int>&& v; // int&template <typename T>
using TRR = T&&;
// v 的类型
TRR<int> v; // int&&
TRR<int>& v; // int&
TRR<int>&& v; // int&&4. 完美转发的原理
template< class T >
T&& forward( typename std::remove_reference<T>::type& t ) noexcept;
template< class T >
T&& forward( typename std::remove_reference<T>::type&& t ) noexcept;std::remove_reference<T> 的作用就是去掉 T 中的引用,它是通过模板特化来实现:
template< class T > struct remove_reference {typedef T type;};
template< class T > struct remove_reference<T&> {typedef T type;};
template< class T > struct remove_reference<T&&> {typedef T type;};根据上述引用折叠规则,如果 T 是 int&,则 T&& 即为 int&;反之,如果 T 是 int&&,则 T&& 为 int&&.
5. forwarding reference
上例函数 f 中的 T&& 实际上被称为 forwarding reference. 它是一种特殊类型的引用,它保留了函数参数的值类别(category),使得可以通过 std::forward 来转发它.
forwarding reference 包括以下两种:
在函数模板中,没有被
const或volatile修饰的、声明为右值引用的类型形参:template<class T> int f(T&& x) { // x is a forwarding reference return g(std::forward<T>(x)); // and so can be forwarded } template<class T> int g(const T&& x); // x is not a forwarding reference: const T is not cv-unqualifiedauto&&,但如果它跟着一个花括号括起的初始值列表,则它不是 forwarding reference:auto&& vec = foo(); // foo() may be lvalue or rvalue, vec is a forwarding reference g(std::forward<decltype(vec)>(vec)); // forwards, preserving value category auto&& z = {1, 2, 3}; // *not* a forwarding reference (special case for initializer lists) for (auto&& x: f()) { // x is a forwarding reference; this is the safest way to use range for loops }
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论