Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c++ - How can I create a std::function with a custom allocator?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...