I have a lambda I'm storing into an std::function
to be called in a separate thread, that looks like this:
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? Specifically in C 17, where I've read custom allocators have been deprecated?
CodePudding user response:
There's no way custom to pass allocator in the current C . std::function
will use global operator new
. It will not even use class's operator new
, instead calling the global one.
However std::function
typically employs small object optimization. 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. With small object optimization, std::function
does not use indirect memory at all.
Your functor has a size of int
, which is very likely to fit small object optimization. You functor will not cause any allocation function to be called when it is put into 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
There are other criteria for small object optimization to engage, specifically noexcept
copy constructor, and not being overly alignend.
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)
CodePudding user response:
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.