Custom allocator in std::vector
Asked Answered
G

1

36

Is it possible to use custom allocator for std::vector internal allocations? If yes, how?

Grappa answered 10/8, 2012 at 7:7 Comment(7)
template < class T, class Allocator = allocator<T> > class vector;Hyposensitize
@LuchianGrigore And how to use that?Grappa
First google link - josuttis.com/libbook/memory/myalloc1.cpp.html and josuttis.com/libbook/memory/myalloc.hpp.htmlHyposensitize
See this recent answer by Howard Hinnant: https://mcmap.net/q/428335/-can-i-assume-allocators-don-39-t-hold-their-memory-pool-directly-and-can-therefore-be-copiedBlanco
What do you mean by "internal allocations"? What aspect of the vector's allocator concept is unclear?Matti
@KerrekSB If I am not mistaken, vector calls new / delete internally when the size changes. Those (de)allocations were meant by the word 'internal'.Grappa
@James: No. vector calls alloc.allocate() and alloc.deallocate() when the size changes.Matti
B
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.

Bellbottoms answered 10/8, 2012 at 7:13 Comment(5)
could you give an exampleMechanical
@Mechanical Click on the link, it has tons of examples.Bellbottoms
This 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.Gualterio
At least I updated the link. The new page is referenced, as cppreference is a wiki. But your point is taken.Bellbottoms
Here is a running example derived from the reference.Vanward

© 2022 - 2024 — McMap. All rights reserved.