在std :: for_each中返回std :: move(f)

时间:2013-08-24 12:16:39

标签: c++ c++11 std move-semantics c++-standard-library

我正在编写标准c ++库的实现用于研究。

C ++ 11标准说for_each返回std::move(f)

template <class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f);

Returns: std::move(f).

我认为函数范围局部变量在返回时是移动构造的。 我应该明确地返回move(f)吗?

1 个答案:

答案 0 :(得分:3)

来自Josuttis的 C ++标准库

您不必也不应该移动()返回值。根据语言规则,标准规定了以下代码

X foo ()
{
X x;
...

return x;
}

保证以下行为:

•如果X具有可访问的副本或移动构造函数,则编译器可以    选择忽略副本。这就是所谓的(命名)返回值    优化((N)RVO),甚至在C ++ 11之前就已经指定了    大多数编译器都支持。

•否则,如果X有移动构造函数,则移动x。

•否则,如果X有复制构造函数,则复制x。

•否则,会发出编译时错误。

来自§25.2.4(for_each)

  

要求:功能应满足 MoveConstructible的要求   (表20)。 [注意:功能不需要满足要求   CopyConstructible(表21).- end note]

使用std::move(f),您可以保证能够从外部读取变异状态。

相关问题