4

Consider the following snippet

#include <iostream>
#include <functional>

using callback = std::function<double (double, double)>;


double sum (double a, double b) {
    return a + b;
}


int main (int argc, char *argv[]) {
    // Shouldn't this leave sum() in an invalid state?
    auto c = std::move(sum);

    std::cout << c(4, 5) << std::endl;
    std::cout << sum(4, 5) << std::endl;

    return EXIT_SUCCESS;
}

I'm converting sum to an rvalue reference, store that in c, and invoke both functions with no noticeable misbehaviors. Why is that? Shouldn't std::move leave sum in an invalid state?

Acsor
  • 1,011
  • 2
  • 13
  • 26
  • 2
    it is mostly same as `std::move(42)`: `move` is pointless – Jarod42 Aug 17 '19 at 09:57
  • I can't find any legitimate reference explaining this in more detail. – Acsor Aug 17 '19 at 09:58
  • A little question, why do you use `callback` instead of `auto`? `auto c = std::move(sum);` – Coral Kashri Aug 17 '19 at 10:09
  • This question was taken out of context, i.e. the original problem applies to another code snippet I modified. – Acsor Aug 17 '19 at 10:13
  • I think you misunderstand what `std::move` does. It cast the result into something that may be moved from, and if it were an unnamed temporary. That allows an object that holds an allocated resource to transfer that resource without allocating a new one. It doesn't do anything interesting for, say, an int or a function pointer. – Eljay Aug 17 '19 at 12:00
  • 1
    A move operation leaves the argument in a *valid* (but unspecified) state, not an invalid one. (In this case the argument, after conversion, is a prvalue so any such changes would not affect `sum`) – M.M Aug 17 '19 at 22:47

1 Answers1

0

You move a pointer to function, not function:

callback c = std::move(sum);

Usage of std::move is redundant here.

isnullxbh
  • 807
  • 13
  • 20