std::function
从右值引用提供构造函数。
按照标准,移动的函数对象会发生什么?会不会是空的,所以再次调用它没有效果?
最佳答案
围绕这个问题有太多的困惑。我会尽量把事情说清楚...
本节描述标准定义对象的移出状态:
17.6.5.15 [lib.types.movedfrom]
Objects of types defined in the C++ standard library may be moved from (12.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.
这是什么意思?这意味着给定一个标准定义的移动对象,您可以对该对象执行任何操作,而无需先验地了解该对象的状态。不需要对当前状态的先验知识的 Action 类别是那些没有先决条件的 Action 。
例如,您可以在移出的 vector
上调用 clear()
,因为 vector::clear()
没有先决条件.但是你不能调用 pop_back()
因为那确实有先决条件。
具体看function
的调用操作符:
20.8.11.2.4 [func.wrap.func.inv]
R operator()(ArgTypes... args) const
Effects: INVOKE(f, std::forward(args)..., R) (20.8.2), where f is the target ob- ject (20.8.1) of *this.
Returns: Nothing if R is void, otherwise the return value of INVOKE (f, std::forward( args)..., R).
Throws: bad_function_call if !*this; otherwise, any exception thrown by the wrapped callable object.
请注意,没有前置条件或 Requires 子句。这意味着调用移动的 function
的 function
的调用运算符不是未定义的行为。无论 function
处于何种状态,您都不会在此调用中违反任何先决条件。
请注意,在任何情况下,规范都没有说调用无效。所以没有效果是不可能的。
调用将调用包装函数,或抛出 bad_function_call
。这是仅有的两个选择。它的行为取决于 function
对象的状态。并且 function
对象的状态是未指定的([lib.types.movedfrom])。
关于c++ - 使用 std::function 移动语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13680587/