Is it possible to use custom allocator for std::vector
internal allocations? If yes, how?
Asked
Active
Viewed 5.1k times
34

TemplateRex
- 69,038
- 19
- 164
- 304

Cartesius00
- 23,584
- 43
- 124
- 195
-
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
-
2See 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
20
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
- 32,434
- 14
- 99
- 159
-
26
-
-
9This 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
-
2At 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
-
5Here 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