【发布时间】:2012-01-11 02:02:22
【问题描述】:
为什么下面的代码有效:
template<typename T1>
void foo(T1 &&arg) { bar(std::forward<T1>(arg)); }
std::string str = "Hello World";
foo(str); // Valid even though str is an lvalue
foo(std::string("Hello World")); // Valid because literal is rvalue
但不是:
void foo(std::string &&arg) { bar(std::forward<std::string>(arg)); }
std::string str = "Hello World";
foo(str); // Invalid, str is not convertible to an rvalue
foo(std::string("Hello World")); // Valid
为什么示例 2 中的左值没有以与示例 1 中相同的方式解析?
另外,为什么标准认为需要在 std::forward 中提供参数类型而不是简单地推导它很重要?简单地向前呼叫就是表明意图,不管是什么类型。
如果这不是标准的东西,只是我的编译器,我正在使用 msvc10,这将解释糟糕的 C++11 支持。
谢谢
编辑 1:将文字“Hello World”更改为 std::string("Hello World") 以生成右值。
【问题讨论】:
-
酒吧发生了什么?编译并不意味着它必须工作。我认为应该分别是
void foo(T1 &arg)和void foo(std::string &arg)。 -
"Hello World"不是右值,它是类型为const char[12]的左值。 -
@AJG85 在 bar 中发生的事情并不重要。 && 表示右值引用。
-
@GMan 为什么“Hello World”是左值?它是不可分配的。我错过了什么鬼鬼祟祟的东西吗?如果我将其更改为 std::string("Hello World") 意味着什么?那么它肯定是一个右值。
-
@AJG85 你刚才描述的是
std::move
标签: c++ c++11 perfect-forwarding