Using function pointers in C ++ 11

The main reason for function pointers is to provide generic callable objects, but in C ++ 11 the way to ensure this is to use std::function , so is there any reason to use function pointers in modern C ++, other than compatibility with C? In other words, is std::function modern version of function pointers, just like std::array versus inline arrays?

+7
c ++ c ++ 11
source share
4 answers

Yes, I would prefer std::function almost universally, but there are several cases where overhead size and indirect std::function values ​​may not be acceptable. For small callable objects, such as function pointers wrapped in std::function , there is usually no additional indirectness and dynamic memory allocation, since the called can fit into std::function , but std::function can be large to hold even larger calls therefore there can be a lot of overhead.

+3
source share

Honestly, I can’t come up with a case where I need std :: function, and that’s why. If I refuse function pointers at all, I probably work at a very low level. Perhaps the reason is that C ++ type inheritance turned out to be too strict, so I am developing my own polymorphism. Alternatively, I can work with a small built-in controller where I really get rid of bytes. In any case, I will rely on myself, not on the compiler, to remember what types I have, etc. I would mostly beat with metal and would like the metal to behave like metal, and not like a lift from Sirius Cybernetics,

The only time I probably want the overhead of std :: function is when I try to do something functional, like closing juggling, but if I want to, I’m unlikely to use C ++ on everything.

+2
source share

On POSIX systems, you get dlopen and dlsym , and you will use them to get function pointers from dynamically loaded plugins.

This is a common use case when function pointers are still useful even with C ++ 14 (see, for example, Qt )

Like many people, the implementation of closures (or std::function ) often requires additional guidance and additional runtime costs.

+1
source share

std::function very convenient and efficient for most use cases. But there is a missing feature: equality.

So, every time you need to compare / filter / search / sort std::function like objects, you need to go back to function pointers in order to implement what you need.

+1
source share

All Articles