6

Here:

http://en.cppreference.com/w/cpp/utility/functional/function

operator bool is described: "Checks whether the stored callable object is valid".

Presumably a default constructed std::function is not valid but is this the only case?

Also, how does it check whether it is valid?

Is the case where operator() raises std::bad_function_call exactly the case where the object is not valid?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
dpj
  • 933
  • 1
  • 7
  • 14

2 Answers2

7

It's poorly written as is, your confusion is justified. By "valid" they mean "has a target".

A std::function "has a target" when it's been assigned a function:

std::function<void()> x; // no target
std::function<void()> y = some_void_function; // has target

x = some_other_void_function; // has target
y = nullptr; // no target

x = y; // no target

They should have either defined "valid" before they used it, or simply stuck with the official wording.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • OK, so the check for validity is just the type check and calling a default constructed `std::function` is exactly the case where `std::bad_function_call` is raised, yup? – dpj Aug 09 '12 at 16:47
  • @user710408: I don't know what you mean by "the check for validity is just the type check". Validity (now assuming the definition "has a target") is determined at run-time, type-checking happens at compile-time. And bad function call happens whever the function isn't valid (has no target), be that from default construction or being explicitly assigned `nullptr`. – GManNickG Aug 09 '12 at 16:55
  • I don't think I knew what I meant either! Thanks :) – dpj Aug 09 '12 at 17:07
  • This answer was exactly what I was looking for, Thank you! – Ravid Goldenberg Jun 06 '13 at 14:33
1

The language standard says

explicit operator bool() const noexcept;

Returns: true if *this has a target, otherwise false.

Meaning that the function has anything to call. The default constructed function obviously does not.

Community
  • 1
  • 1
Bo Persson
  • 90,663
  • 31
  • 146
  • 203