c++ - 为什么在这个函数中返回时使用std::move

标签 c++ c++11 stl

我刚刚读了 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/

相关文章:

c++ - XCode 程序优雅关闭

c++ - 智能指针是否能够从容器中删除对其对象的其他引用?

c++ - 如果函数是在类范围内声明的,则 constexpr 不起作用

c++ - 这段代码会使那些 vector 对齐吗?

c++ - 如何找出STL版本

c++ - C++标准是否保证cin、cout等先创建后销毁?

c++ - 不能在从 std::vector 继承的类中使用 typedef 迭代器

具有二进制数据的 C++ fstream << 和 >> 运算符

c++ - 未按预期调用移动构造函数

c++ - 如何在c++中高效地在 map 中创建 map