在std :: for_each中返回std :: move(f) [英] Returning std::move(f) in std::for_each

查看:208
本文介绍了在std :: for_each中返回std :: move(f)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写标准c ++库的实现以供学习。

I'm writing an implementation of standard c++ library for study.

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

The C++11 standard says that for_each returns std::move(f).

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

Returns: std::move(f).

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

I thought that function scope local variable is move-constructed when it's returned. Should I return move(f) explicitly?

推荐答案

从Josuttis的 C ++标准库

From Josuttis 's The C++ Standard Library

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

You don’t have to and should not move() return values. According to the language rules, the standard specifies that for the following code

X foo ()
{
X x;
...

return x;
}

以下行为得到保证:

•如果X有一个可访问的复制或移动构造函数,编译器可能会
选择删除复制。这是所谓的(命名)返回值
优化((N)RVO),它在C ++ 11之前被指定,并且是大多数编译器支持的

• If X has an accessible copy or move constructor, the compiler may choose to elide the copy. This is the so-called (named) return value optimization ((N)RVO), which was specified even before C++11 and is supported by most compilers.

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

• Otherwise, if X has a move constructor, x is moved.

一个复制构造函数,x被复制。

• Otherwise, if X has a copy constructor, x is copied.

否则会产生编译时错误。

• Otherwise, a compile-time error is emitted.

§25.2.4(for_each)

From §25.2.4 (for_each)


需要:功能必须符合 MoveConstructible
(表20)
。 [注意:函数不需要满足
的要求CopyConstructible(表21).- end note]

Requires:Function shall meet the requirements of MoveConstructible (Table 20). [Note:Function need not meet the requirements of CopyConstructible (Table 21).—end note]

c $ c> std :: move(f)您可以保证能够从外部读取突变状态。

With std::move(f) you can be guaranteed of being able to read the mutated state externally.

这篇关于在std :: for_each中返回std :: move(f)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆