Move semantic with std::function

19,673

Solution 1

Under 20.8.11.2.1p6, function(function &&f) leaves f in a valid state with an unspecified value.

The empty state is a valid state, so you should expect that the moved-from function object can be empty.

Because function performs type erasure, and function objects can be arbitrarily expensive, the optimisation to leave the moved-from object empty makes sense:

std::function<void()> g{std::bind{f, std::array<int, 1000>{}}};
std::function<void()> h{std::move{g}};

After h has been constructed by move from g, one would expect the contained bind have been transferred from g to h rather than copying, so g would be left empty.

For the following program, gcc 4.5.1 prints empty:

#include <functional>
#include <iostream>
void f() {}
int main() {
    std::function<void()> g{f}, h{std::move(g)};
    std::cout << (g ? "not empty\n" : "empty\n");
}

This is not necessarily the most optimal behaviour; inlining small callables (e.g. function pointers) creates a situation where copying the callable is more efficient than moving it and emptying the moved-from object, so another implementation could leave g in a non-empty callable state.

Solution 2

There is too much confusion around this question. I'm going to try to lay things out clearly...

This section describes the moved-from state of std-defined objects:

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.

What does this mean? This means that given a std-defined moved-from object, you can do anything with that object that doesn't require a priori knowledge of the state of that object. The class of actions that require no a priori knowledge of the current state are those that have no preconditions.

For example you can call clear() on a moved-from vector because there are no preconditions on vector::clear(). But you can't call pop_back() because that does have preconditions.

Looking specifically at the call operator of 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.

Note that there is no precondition or Requires clause. That means that calling the call operator of function of a moved-from function is not undefined behavior. No matter what state the function is in, you're not going to violate any preconditions with this call.

Note that in no case does the specification say that the call will have no effect. So having no effect is not a possibility.

The call will either call the wrapped function, or throw a bad_function_call. Those are the only two choices. And which behavior it has depends on the state of the function object. And the state of the function object is unspecified ([lib.types.movedfrom]).

Solution 3

What happens to the moved function object by standard?

It will be in a valid state (thus the object can be used), but the actual state that it is in is unspecified. The last part means that calling any function that requires the object to be in a specific state will not necessarily work.

Will it be empty so that calling it again has no effects?

You cannot assume it will be. Calling the function requires that it actually have a function to call. That's part of its state. And since the state is unspecified, the results of calling it are unspecified.

If you want to use the object in some meaningful way again, simply create a new function and assign it to it:

function<...> old;
function<...> new_ = std::move(old);
old = function<...>(...); //Reset to known state.
old(...); //Call is well-defined.
Share:
19,673

Related videos on Youtube

Martin
Author by

Martin

Updated on September 15, 2022

Comments

  • Martin
    Martin over 1 year

    std::function provides a constructor from an rvalue ref. What happens to the moved function object by standard? Will it be empty so that calling it again has no effects?

    • juanchopanza
      juanchopanza over 11 years
      It depends on the class' move copy constructor and/or move assignment operator.
    • Martin
      Martin over 11 years
      @juanchopanza What do you mean? Of course it depends on the move constructor. What does it do to the original function object? Will it be empty after being moved?
    • juanchopanza
      juanchopanza over 11 years
      Sorry, I thought you meant the arguments to the variadic constructor via a bind object.
  • Martin
    Martin over 11 years
    Does that also mean that the function object being moved can be called without any effects?
  • Steve Jessop
    Steve Jessop over 11 years
    @Martin: the effects of calling it are unspecified or undefined, I'm not quite sure which (i.e. no, you cannot call it). One example of a valid state of a function object is that it wraps a null function pointer. Calling that would have undefined behavior.
  • Alok Save
    Alok Save over 11 years
    @Martin: In simple words, the function object is valid enough to exist but not valid enough to be used.
  • Arne Mertz
    Arne Mertz over 11 years
    @Martin no. If f is empty after being move, that means it throws bad_function_call if you invoke it.
  • Martin
    Martin over 11 years
    @SteveJessop: Will std::function::operator bool() return false at least?
  • Nicol Bolas
    Nicol Bolas over 11 years
    @Martin: "Unspecified" means unspecified. You don't know, so you can't assume it will.
  • Steve Jessop
    Steve Jessop over 11 years
    @Martin: if you want the moved-from object to have particular behavior then you should assign a value to it after the move. Otherwise, assume that the only things you can validly do with it are assign to it, copy/move from it or destroy it. That is, it can perform object lifecycle operations but nothing else.
  • Admin
    Admin over 8 years
    In C++11 if you use a std::function in a resource manager and call it in the destructor, you'll get std::terminate()ed if the function is empty, because that's what you get for throwing in a destructor. So it's a small change of affairs: std::bad_function_call throw followed by std::terminate().
  • Howard Hinnant
    Howard Hinnant over 8 years
    @villageidiot: Change from what? std::function became standard at the same time as move semantics, and noexcept on destructors (C++11).
  • Admin
    Admin over 8 years
    Sorry, bad wording. I mean a "mere" throw becomes a call to std::terminate() if it's done in a destructor. Is that right?
  • Howard Hinnant
    Howard Hinnant over 8 years
    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.