【发布时间】:2015-03-21 00:36:18
【问题描述】:
案例1:我正在写一个简单的移动构造函数:
ReaderValue::ReaderValue(ReaderValue && other)
{
moveAlloc(other);
}
ReaderValue 类中的moveAlloc 函数原型为:
void moveAlloc(ReaderValue && other);
我从 gcc 4.8 得到错误:
cannot bind 'ReaderValue' lvalue to 'ReaderValue&&'
所以我需要明确地调用它才能编译:
moveAlloc(std::move(other));
案例 2:现在 ReaderValue 有一个 std::string stringData 成员
我再做一个构造函数:
ReaderValue(std::string && otherString)
: stringData(otherString)
{
}
这行得通,我不需要 std::move 将 otherString 传递给 stringData 构造函数
问题:在第一种情况下,我需要显式调用 std::move 以将右值传递给函数的根本原因是什么?错误消息说 other 是左值,而它看起来确实像右值引用。为什么不是第二种情况?
(请不要回复实际的实现,或者我为什么需要这样做,等等等等……这只是一个基本的语言问题)
【问题讨论】:
-
也许你需要 std::forward 你的
other而不是移动? -
使用forward和move here有什么不同吗?
标签: c++11 constructor move rvalue-reference