<div dir="ltr"><div dir="ltr"><div dir="ltr"><div dir="ltr"><div dir="ltr">On Fri, Jan 8, 2021 at 5:45 AM Cyril Makloufi via cfe-dev <<a href="mailto:cfe-dev@lists.llvm.org">cfe-dev@lists.llvm.org</a>> wrote:</div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-style:solid;border-left-color:rgb(204,204,204);padding-left:1ex"><div dir="ltr"><div id="gmail-m_7133911533009612547divtagdefaultwrapper" dir="ltr" style="font-size:12pt;color:rgb(0,0,0);font-family:Calibri,Helvetica,sans-serif,Helvetica,EmojiFont,"Apple Color Emoji","Segoe UI Emoji",NotoColorEmoji,"Segoe UI Symbol","Android Emoji",EmojiSymbols">
<p style="font-family:Calibri,Helvetica,sans-serif,serif,EmojiFont">When using std::function instead of function pointer (see the sample of code) on Mac, we get a huge difference between size of generated binary (80ko when using function pointer and 157ko whit
 std::function).</p></div></div></blockquote><div>This is expected. std::function<void()> is a library type. It does "type erasure," a C++ technique which you can learn about here:</div><div><a href="https://www.youtube.com/watch?v=tbUCHifyT24">https://www.youtube.com/watch?v=tbUCHifyT24</a> ("Back to Basics: Type Erasure", CppCon 2019)<br></div><div>Contrast with core-language lambda expressions:</div><div><a href="https://www.youtube.com/watch?v=3jCOwajNch0">https://www.youtube.com/watch?v=3jCOwajNch0</a> ("Back to Basics: Lambdas from Scratch", CppCon 2019)<br></div><div><br></div><div>You can do a lot of things with `std::function<void()> f` that you can't do with `void (*f)()`; for example, `std::function<void()> f` can hold a copy of a lambda which itself has captures.</div><div><br></div><div>    int i = 42;</div><div>    std::function<void()> f = [&]() { std::cout << i; };  // OK</div><div>    void (*g)() = [&]() { std::cout << i; };  // Ill-formed</div><div><br></div><div>You pay for this flexibility in code size (and speed) (and, in many cases, heap-allocations).</div><div><br></div><div>Additionally, std::function is notoriously inefficient <i>even as type-erased types go</i>. This is partly because the paper standard requires it to do so much (e.g. the .target_type() method); and partly because its implementation was done ~15 years ago and maybe we'd like to apply some lessons learned since then, but that would break ABI.</div><div><a href="https://quuxplusone.github.io/blog/2019/01/06/hyper-function/">https://quuxplusone.github.io/blog/2019/01/06/hyper-function/</a><br></div><div><br></div><div>HTH,</div><div>Arthur</div></div></div></div></div></div>