Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 960
Inbae Jeong Avatar asked Aug 24 '13 12:08

Inbae Jeong


People also ask

Can std :: function be moved?

Yes, unless you catch it, or unless you mark the destructor noexcept(false) . And in the latter case you have to be pretty careful or it may result in std::terminate() anyway.

What happens when you to std :: move?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

What is std:: for_ each?

applies a function object to the first n elements of a sequence. (function template) ranges::for_each. (C++20) applies a function to a range of elements.


1 Answers

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.

like image 145
P0W Avatar answered Oct 03 '22 02:10

P0W