How can I create a std::function with a custom allocator?
allocator, c++, c++11
Solution
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.
Problem
To save some code lets say I have a custom allocator named `MyAlloc` which I have successfully used with a `std::vector<int>` as follows: ``` std::vector<int,MyAlloc<int>> vec; ``` now I want to save a lambda in a std::function using the custom allocator, how do I do it? My failed attempt: ``` int i[100]; std::function<void(int)> f(MyAlloc<void/*what to put here?*/>{},[i](int in){ //... }); ``` Update: allocators in std::function have been deprecated