Returning std::move(f) in std::for_each

有些话、适合烂在心里 提交于 2019-11-28 07:37:07

问题


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

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).

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


回答1:


From Josuttis 's The C++ Standard Library

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;
}

the following behavior is guaranteed:

• 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.

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

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

• Otherwise, a compile-time error is emitted.

From §25.2.4 (for_each)

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

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



来源:https://stackoverflow.com/questions/18418470/returning-stdmovef-in-stdfor-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!