6

I've found the tr.func.require section of the specification that requires std::function to be copy-constructable in C++11, and I've seen plenty of explanations of why this implies that the functors used to construct std::function have to be copyable, but why did the C++11 standard made std::function copyable in the first place, instead of making it a move-only type?

Peter Milley
  • 2,768
  • 19
  • 18
  • 4
    Probably because a lot(maybe all, can't remember) of the algorithms defined by the standard are allowed to copy the functor passed to them. – NathanOliver May 08 '17 at 16:12
  • 2
    std::function should be usable like a C function pointer, otherwise it would be pretty useless. This means unrestricted cooying. If I want to store copies of a function at two different locations, how would I do that with move-only functions? – n. m. could be an AI May 08 '17 at 16:21
  • NathanOliver, is that requirement explicitly spelled out anywhere? Spot-checking, I'm not finding any such requirement documented in most of the algorithms, except (so far) the parallel version of for_each introduced in C++17. – Peter Milley May 08 '17 at 16:33
  • 2
    we need `std::unique_function` – Guillaume Racicot May 08 '17 at 16:38

1 Answers1

2

std::function was implemented before C++11 when move-semantics were not yet available (it stems from boost::function and was part of TR1).

My guess is that std::function was specified (and perhaps voted into the standard) before move semantics. And the didn't have time to review all the rest of the standard in light of this. See also this answer about why shared_ptr deleters have to be CopyConstructible.

Also, for compatibility reasons, it sounds unreasonable to all-of-a-sudden make std::function move constructible and remove its copy-constructor.

Community
  • 1
  • 1
jotik
  • 17,044
  • 13
  • 58
  • 123
  • Are you certain? http://en.cppreference.com/w/cpp/utility/functional/function suggests that std::function was introduced in C++11. – Peter Milley May 08 '17 at 17:00
  • 3
    @PeterMilley: Yes, but the process of producing C++11 took ~4 years. `std::function` was added to C++11 first, then move semantics were added to C++11 later. They chose to "ship" C++11 rather than reviewing all the existing algorithms in detail. – Mooing Duck May 08 '17 at 17:19