How can I create a std::function with a custom allocator?
According to the standard, you need to give a tag type as the first argument to indicate that you want to use a custom allocator:
std::function<void(int)> f(std::allocator_arg, MyAlloc<char>{}, [i](int in){
//...
});
As pointed out by @Casey and @Potatoswatter in the comments, the template argument type given to the allocator does not matter, as long as it's an object type. So char
is fine here.
Update for C++17: It turns out that the allocator support for std::function
has a number of fundamental issues, which lead to it being deprecated in C++17. If you nonetheless insist on using it, be sure to carefully check your implementation before doing so. GCC's standard library never implemented those functions, but even if your standard library does, it might not behave the way that you expect.