Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is a 'valid' std::function?

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?

like image 442
dpj Avatar asked Aug 09 '12 16:08

dpj


People also ask

How do you know if a std function is valid?

You can check if a std::function is empty with std::function::operator bool . true: if the object is callable. foo is not empty. bar is empty.

What is the function of std in C++?

Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

What is the type of std :: function?

std::function is a type erasure object. That means it erases the details of how some operations happen, and provides a uniform run time interface to them. For std::function , the primary1 operations are copy/move, destruction, and 'invocation' with operator() -- the 'function like call operator'.

Why do we need std :: function?

std::function can hold more than function pointers, namely functors. Live example on Ideone. As the example shows, you also don't need the exact same signature, as long as they are compatible (i.e., the parameter type of std::function can be passed to the contained function / functor).


2 Answers

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.

like image 55
GManNickG Avatar answered Oct 15 '22 05:10

GManNickG


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.

like image 42
Bo Persson Avatar answered Oct 15 '22 05:10

Bo Persson