Skip to content

Comment on Why C++ Is Terrifyingparent

Comments

The tweet is certainly loaded, hence the point of this HN post lol.

First of all there's std::function, which uses Type Erasure https://blog.the-pans.com/type-erasure/. It means std::function<void(int)> can be the type of anything callable that takes an int and returns void (lambda, function pointer, object with operator() overload, etc.). Notice they are of different types! Hence Type Erasure.

How std::function manages its memory is poorly specified. But the standard at least states that if it's initialized from a function pointer (free, no capture), it's guaranteed that it won't allocate. https://en.cppreference.com/w/cpp/utility/functional/functio...

When the target is a function pointer or a std::reference_wrapper, small object optimization is guaranteed, that is, these targets are always directly stored inside the std::function object, no dynamic allocation takes place.

In this case, std::function is trivially copyable. However, there's no way to know this at compile time, exactly because the type is erased in std::function.

Hence Type Erasure

So basically duck typing?

Type erasure is rather like Go interfaces.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.