sizeof of std :: function< void(int&)>类型 [英] Sizeof of std::function<void(int&)> type

查看:252
本文介绍了sizeof of std :: function< void(int&)>类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: function< void(int&)> 从C ++ 11中得到的 sizeof = 32 ?如果我将函数引用存储为指针,它只需要 8字节(在64位机器上)。

What kind of magic does the std::function<void(int&)> from C++11 that its sizeof = 32? If I'd store the function reference as a pointer, it'd cost only 8 bytes (on a 64 bit machine).

推荐答案

对于 std :: function< Signature> 它是对象大小和分配之间的折衷:对于小函数对象,需要避免分配。另一方面,这样做增加了对象大小。为了使小函数优化有用并且在实际调用对象时不引入开销,对象大小需要是至少两个指针加上一些存储器以存储简单的函数对象。似乎32字节的大小正是这个(在 sizeof(T *)是8)的系统。

For std::function<Signature> it is a trade-off between object size and allocation which is interesting: For small function objects it is desirable to avoid an allocation. On the other hand, doing so increases the object size. For the small function optimization to be useful and not introduce overheads when actually calling the object, the object size needs to be at least two pointers plus some memory to store simple function objects. It seems that a size of 32 bytes is exactly this (on a system where sizeof(T*) is 8).

也就是说,在内部一个 std :: function< Signature> 对象存储一个继承层次结构:基类提供了被调用的接口,委托给一个模板化派生实现调用接口(加,可能,一些 clone()功能)。在针对大小优化的实现中,函数对象将仅保留指向基础的指针,但是为了避免分配,它将搁置一些内部存储以将整个对象分配并指向该对象(内部指针避免在实际调用函数对象)。对象所需的存储器是虚拟函数指针加上实际函数对象的任何数据, std :: function< Signature> 对象被初始化。为了容纳成员函数及其对象,似乎还有两个字是相当小的。

That is, internally a std::function<Signature> object stores an inheritance hierarchy: The base class provides the interface to be called, delegating to a templatized derived which implements the call interface (plus, probably, some clone() functionality). In an implementation optimized for size the function object would just keep a pointer to the base, but to avoid allocation it would set aside some internal storage to allocate the entire object in and point to this object (the internal pointer avoids a condition when actually calling the function object). The memory needed for the object is a virtual function pointer plus any data for the actual function object the std::function<Signature> object is initialized with. To accommodate member functions with their object it seems that two more words is reasonably small.

这篇关于sizeof of std :: function&lt; void(int&amp;)&gt;类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆