简体   繁体   中英

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 provide it would be to use std::function , so is there any reason to use function pointers in modern C++ apart from compatibility with C? In other words, is std::function a modern version of function pointers, exactly like std::array vs built-in arrays?

Yes I'd prefer std::function nearly everywhere but there are few cases where size overhead and indirection of std::function may not be acceptable. For small callables like function pointers wrapped in std::function , there is typically no additional indirection and no dynamic memory allocation since the callable fits into the std::function but std::function may be big to hold even bigger callables so there may be a big space overhead.

To be honest, I can't think of a case where I'd need std::function, and here's why. If I'm bouncing function pointers around at all, then I'm probably working at a very low level. Perhaps the reason is that C++-style inheritance has proven too restrictive so I'm designing my own polymorphism. Alternatively, I might be working on a small embedded controller where I'm really shaving off the bytes. Either way, I'll be relying on myself, and not on the compiler, to remember what types I've got etc. I'd basically be banging metal and want the metal to behave like metal, not like an elevator from Sirius Cybernetics.

The only case where I'm likely to want the overhead of std::function is if I'm trying to do something functional, like juggling closures, but if I want that then I'm unlikely to be using C++ at all.

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

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

And as many people observed, the implementation of closures (or of std::function ) would often require extra indirections and extra runtime costs.

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

So, every time you need to compare/filter/search for/sort std::function like objects, you have to fall back to function pointers to implement what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM