Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom allocator in std::vector

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

like image 487
Cartesius00 Avatar asked Aug 10 '12 07:08

Cartesius00


People also ask

How do you allocate a std::vector?

An std::vector manages its own memory. You can use the reserve() and resize() methods to have it allocate enough memory to fit a given amount of items: std::vector<int> vec1; vec1. reserve(30); // Allocate space for 30 items, but vec1 is still empty.

What is a std :: allocator?

std::allocator is the default memory allocator for the standard library containers, and you can substitute your own allocators. This allows you to control how the standard containers allocate memory.

Is std::vector heap allocated?

std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.

Is std::vector stack allocated?

Although std::vector can be used as a dynamic array, it can also be used as a stack.


1 Answers

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.

like image 177
bitmask Avatar answered Nov 02 '22 23:11

bitmask