Use std::function not.
Or why blindly copying patterns from other languages is not always a good idea.
It’s easy to spot most former Java programmers by how they write C++. But while always using the new operator for instantiation is obviously not a good idea, some other “signature moves” are harder to notice.
Our privacy infrastructure APIs allow access only to data with compatible policy. Its implementation is somewhat involved reflecting essential domain complexity but since most of it has nothing to do with our goal for today, we’ll take a look at a tiny snippet below instead
The idea is that function func would be invoked only for authorized clients. Looks reasonable, right? Let’s use it in following 2 scenarios
Even though we prevent compiler from inlining run1 function, we still expect a reasonably efficient assembly for such trivial usages. But what we get instead is somewhat disappointing
Ouch. Well, turns out std::function is using type-erasure so it’s not necessarily the most optimization friendly type. Fortunately C++ has a much better and more powerful solution - templates!
Doesn’t look scary, does it? Let’s put it to the same test as run1
and the result looks very different indeed
Since type erasure doesn’t mess with compiler’s ability to perform its magic, the lambda version ends up with 0 extra overhead and func pointer results in a single tail call.
C++ is a seriously powerful tool and deserves time investment to make the best use out of it. So the book below is not the best one to learn C++