将lambda存储到std ::功能的可能存储浪费
带有空捕获列表的lambda表达式对象的大小为1
,但是如果将其存储到std:function
中,它的大小将变为48(在我的平台上),
想象一下当您拥有一个存储数千个容器时函数的
内存使用情况将增加48倍的时间,如果将它们存储到std :: function
甚至捕获小对象的lambda对象(例如8尺度的指针)也比std ::函数
您是否有更好的主意来保存不必要的空间使用?
The size of a lambda expression object with an empty capture-list is 1
But if you store it into std:function
, its size becomes 48 (on my platform)
Imagine when you have a container that stores thousands of functions
The memory usage will be 48-times bigger if you store them into std::function
Even a lambda object capturing a small object (like an 8-sized pointer) is much smaller than a std::function
Do you have any better idea to save that unnecessary space-usage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您不需要知道功能类型的价格。所有
std :: function< void()>
s均可互换,无论它们来自哪个lambda。如果要在向量中存储很多相同类型的函数(带有不同的捕获),则可以使其成为函数,而不是lambda(以便它具有名称),并制作该类型<的向量 /em>。示例:使用lambda:
使用Foundor:
IMO这有点没用,因为我们不妨存储一个INT的向量并停止假装它们是函数。当您拥有许多相同类型的函子时,您已经知道他们在做什么,所以就这样做。实际上,上面的代码只是下面的代码,但采用了额外的步骤:
This is the price you pay for not needing to know the type of the function. All
std::function<void()>
s are interchangeable no matter which lambda they came from. If you want to store lots of the same type of function (with different captures) in a vector, you can make it a functor instead of a lambda (so that it has a name) and make a vector of that type.Example: With lambda:
With functor:
IMO this is a bit useless, because we might as well store a vector of ints and stop pretending they are functions. When you have many functors of the same type you already know what they do, so just do it. Really, the code above is just the code below, but with extra steps: