Is it possible to use custom allocator for std::vector internal allocations? If yes, how?
Asked
Active
Viewed 4.3k times
30
TemplateRex
- 67,479
- 19
- 160
- 290
Cartesius00
- 22,610
- 41
- 119
- 191
-
3template < class T, **class Allocator = allocator
** > class vector; – Luchian Grigore Aug 10 '12 at 07:08 -
@LuchianGrigore And how to use that? – Cartesius00 Aug 10 '12 at 07:08
-
4First google link - http://www.josuttis.com/libbook/memory/myalloc1.cpp.html and http://www.josuttis.com/libbook/memory/myalloc.hpp.html – Luchian Grigore Aug 10 '12 at 07:11
-
@LuchianGrigore That's it, thanks. – Cartesius00 Aug 10 '12 at 07:12
-
1See this recent answer by Howard Hinnant: http://stackoverflow.com/a/11703840/819272 – TemplateRex Aug 10 '12 at 07:20
-
What do you mean by "internal allocations"? What aspect of the vector's allocator concept is unclear? – Kerrek SB Aug 10 '12 at 08:21
-
@KerrekSB If I am not mistaken, `vector` calls `new` / `delete` internally when the size changes. Those (de)allocations were meant by the word 'internal'. – Cartesius00 Aug 10 '12 at 09:56
-
1@James: No. `vector` calls `alloc.allocate()` and `alloc.deallocate()` when the size changes. – Kerrek SB Aug 10 '12 at 10:02
1 Answers
19
You basically have to implement your allocator type to conform to the Allocator concept.
The linked page lists all requirements of that type, but the core functionality is implemented in the allocate member function.
bitmask
- 27,748
- 13
- 86
- 145
-
20
-
-
8This is exactly the reason why link only answers are *bad*! The page doesn't exist anymore. Pointing towards examples in the broken link is even worse. – dtell Jun 18 '18 at 12:03
-
1At least I updated the link. The new page is referenced, as cppreference is a wiki. But your point is taken. – bitmask Jun 18 '18 at 12:29
-
1Here is a [running example](https://godbolt.org/z/7fnj1rGr9) derived from the [reference](https://en.cppreference.com/w/cpp/named_req/Allocator). – schoetbi Oct 27 '21 at 05:49