[英]Can I place an std::function's capturing lambda in my own memory?
I have a lambda I'm storing into an std::function
to be called in a separate thread, that looks like this:我有一个 lambda 我正在存储到一个
std::function
中以在单独的线程中调用,它看起来像这样:
void * specialMalloc(size_t size); // provides annointed memory; beloved by all
int n;
std::function f = [=]()mutable -> void {
printf("%i", n);
};
Is it possible to create a std::function f
that takes this lambda and it's int n
, and asks specialMalloc()
to carefully prepare memory to place it into?是否可以创建一个
std::function f
接受这个 lambda 并且它是int n
,并要求specialMalloc()
仔细准备 memory 以将其放入? Specifically in C++17, where I've read custom allocators have been deprecated?特别是在 C++17,我在哪里读到自定义分配器已被弃用?
There's no way custom to pass allocator in the current C++. std::function
will use global operator new
.无法自定义在当前 C++ 中传递分配器。std
std::function
将使用全局operator new
。 It will not even use class's operator new
, instead calling the global one.它甚至不会使用类的 operator
new
,而是调用全局的。
However std::function
typically employs small object optimization.然而
std::function
通常采用小型 object 优化。 At least you expect it to engage for pointer-sized functors.至少您希望它能够处理指针大小的仿函数。 Real implementations have buffer for small object optimization for 2-3 pointers, MSVC has much more.
真正的实现有针对 2-3 个指针的小 object 优化的缓冲区,MSVC 有更多。 With small object optimization,
std::function
does not use indirect memory at all.通过小型 object 优化,
std::function
根本不使用间接 memory。
Your functor has a size of int
, which is very likely to fit small object optimization.您的仿函数的大小为
int
,很可能适合小型 object 优化。 You functor will not cause any allocation function to be called when it is put into std::function
.您的仿函数不会导致任何分配 function 在放入
std::function
时被调用。
For larger functors, you can make their data indirect, and allocate it on your own, so that they'll make use of small object optimization, and thus will not use the global operator new
对于较大的仿函数,可以将它们的数据间接化,自己分配,这样它们就会利用小的 object 优化,从而不会使用全局 operator
new
There are other criteria for small object optimization to engage, specifically noexcept
copy constructor, and not being overly alignend.小型 object 优化还有其他标准可以参与,特别是
noexcept
copy constructor,并且不会过度对齐。
Unfortunately, there's no standard way to query in compile-time whether small object optimization apply, and it is not required by the standard (although recommended for some types of functors)不幸的是,没有标准的方法可以在编译时查询小 object 优化是否适用,标准也没有要求(尽管推荐用于某些类型的函子)
I think there's not a good way to do this.我认为没有一个好的方法来做到这一点。
Well, std::function
had a constructor that took a custom allocator but this functionality was removed in C++17 .好吧,
std::function
有一个采用自定义分配器的构造函数,但此功能已在 C++17 中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.