本文介绍了为什么std :: forward在这个上下文中无用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 std :: forward 在此上下文中无用:

It has come to my attention that std::forward is useless in this context:

void consumeObject(std::unique_ptr<Object>&& robj) {
  myvector.emplace_back(std::forward<std::unique_ptr<Object>>(robj));
}

为什么?我认为,当一个右值引用绑定到一个函数参数(即我可以通过名称引用它)成为一个左值的范围,为了被传递需要被转换到一个右值引用(如完美转发)。

Why is that? I thought that by the time an rvalue reference binds to a function parameter (i.e. I can reference it by name) it becomes an lvalue in that scope and in order to be passed forward needs to be casted to an rvalue reference (as in perfect forwarding).

为什么是错误/无用的?

Why is it wrong/useless?

推荐答案

不是错误在这里(本身)使用 std :: forward ,但这是不恰当的,因此误导(在这个意义上,

It's not wrong to use std::forward here (per se), but it is inappropriate and thus misleading (in that sense, you could say that it is actually wrong).

拼写将某个内容转换为其类型的右值引用的方式是 std :: move 。这是 std :: move 所做的只是,它是一个 static_cast< T&& code>您不必说明 T

The way you spell "cast something to an rvalue reference to its type" is std::move. That is the only thing that std::move does—it's a static_cast<T&&> where you don't have to spell out the T.

std :: forward 是一种不同的野兽,旨在与完美转发配合使用。完美转发仅发生在模板中,其中 。转发引用是一种引用,由于语言中的特殊规则,引用可以推导为左值引用或右值引用。在这里,您需要 std :: forward< T> 重新设置适当的值类别(lvalue或rvalue)。

std::forward is a different beast, intended for use with perfect forwarding. Perfect forwarding only occurs in templates, where forwarding references are possible. A forwarding reference is a reference which, thanks to a special rule in the language, can deduce to either an lvalue reference or an rvalue reference. There, you need std::forward<T> to re-instate the appropriate value category (lvalue or rvalue).

玩具示例:

void print(int &)
{
  std::cout << "Lvalue\n";
}

void print(int &&)
{
  std::cout << "Rvalue\n";
}

template <class T>
void perfectForwarder(T &&v)
{
  print(std::forward<T>(v));
}

int main()
{
  int i;
  perfectForwarder(i);
  perfectForwarder(std::move(i));
  perfectForwarder(42);
}

输出将是:

这篇关于为什么std :: forward在这个上下文中无用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 04:54