Sizeof of std::function type

前端 未结 2 950
离开以前
离开以前 2021-02-12 12:18

What kind of magic does the std::function from C++11 that its sizeof = 32? If I\'d store the function reference as a pointer, it\

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 12:26

    std::function is indeed magic, as it can be constructed from any callable object! It will happily store any amount of state for you, even if on the surface you retain a measly void(int&) signature.

    There's certainly a price attached to this magic, which typically uses some sort of type erasure (i.e. a dynamic allocation and virtual dispatch) internally. The details vary, but the resulting objects are certainly "heavy" — which is why they should be avoided in favour of auto and templates whenever feasible!

提交回复
热议问题