我刚刚读了 STL 的 Visual Studio 实现的 Algorithm.h header ,发现了以下代码:
template<class _InIt,
class _Fn1> inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{ // perform function for each element
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER(_Func);
_For_each(_Unchecked(_First), _Unchecked(_Last), _Func);
return (_STD move(_Func));
}
...代码的重要部分如下:
template<class _InIt, class _Fn1>
inline _Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{ // perform function for each element
_For_each(_Unchecked(_First), _Unchecked(_Last), _Func);
return (std::move(_Func));
}
...这是 _For_each
的签名功能
template<class _InIt,
class _Fn1> inline
void _For_each(_InIt _First, _InIt _Last, _Fn1& _Func)
我的问题是为什么 std::move
在这种情况下返回时需要吗?
并完成问题:在什么情况下需要使用std::move
当从函数返回时?我认为以务实的方式获取这些信息可能会很有用。
最佳答案
您的问题的简短答案是 C++11 标准是这么说的。需要实现 for_each 来返回可移动构造的函数对象/指针。
来自标准:
25.2.4 For each [alg.foreach]
template Function for_each(InputIterator first, InputIterator last, Function f);
1 Requires: Function shall meet the requirements of MoveConstructible (Table 20). [ Note: Function need not meet the requirements of CopyConstructible (Table 21). — end note ]
2 Effects: Applies f to the result of dereferencing every iterator in the range [first,last), starting from first and proceeding to last - 1. [ Note: If the type of first satisfies the requirements of a mutable iterator, f may apply nonconstant functions through the dereferenced iterator.— end note ]
3 Returns: std::move(f).
4 Complexity: Applies f exactly last - first times.
5 Remarks: If f returns a result, the result is ignored.
项目 #3 需要 std::for_each
返回 std::move(fn)
。
And my question is why is the std::move required when returning in this case?
标准要求它的原因是为了保证返回值是可移动构造的函数对象。
And for completing the question: In what cases is required to use std::move when returning out of a function?
如果您需要或希望函数的返回值是可移动构造的,则可以使用return std::move(...)
。这允许您在函数退出时访问返回值的状态(在 for_each
示例中,函数对象/指针的状态)。
作为引用,该标准的表 20 内容如下:
Table 20 — MoveConstructible requirements [moveconstructible]
Expression Post-condition
T u = rv; u is equivalent to the value of rv before the construction
T(rv) T(rv) is equivalent to the value of rv before the construction
[ Note: rv remains a valid object. Its state is unspecified — end note ]
关于c++ - 为什么在这个函数中返回时使用std::move,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21004879/