The notation for std::function is quite nice when compared to function pointers. However, other than that, I can't find a use case where it couldn't be replaced by pointers. So is it just syntactic sugar for function pointers?
They are not the same at all. std::function is a complex, heavy, stateful, near-magic type that can hold any sort of callable entity, while a function pointer is really just a simple pointer. If you can get away with it, you should prefer either naked function pointers or auto - bind / auto -lambda types.
2. What will we not do with function pointers? Explanation: As it is used to execute a block of code, So we will not allocate or deallocate memory.
Instances of std::function can store, copy, and invoke any CopyConstructible Callable target -- functions (via pointers thereto), lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.
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.
std::function
is designed to represent any kind of callable object. There are plenty of callable objects that cannot be represented in any way by a function pointer.
A functor:
struct foo {
bool operator()(int x) { return x > 5; }
};
bool (*f1)(int) = foo(); // Error
std::function<bool(int)> f2 = foo(); // Okay
You cannot create an instance of foo
and store it in a bool(*)(int)
function pointer.
A lambda with a lambda-capture:
bool (*f1)(int) = [&](int x) { return x > y; }; // Error
std::function<bool(int)> f2 = [&](int x) { return x > y; }; // Okay
However, a lambda without a capture can be converted to a function pointer:
The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.
Implementation-defined callable return values:
bool foo(int x, int y) { return x > y; };
bool (*f1)(int) = std::bind(&foo, std::placeholders::_1, 5); // Error (probably)
std::function<bool(int)> f2 = std::bind(&foo, std::placeholders::_1, 5); // Okay
std::bind
's return value is an implementation-defined callable object. Only how that object may be used is specified by the standard, not its type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With