Std::allocator
lastmod 2018-08-17created 2015-09-1113 edits
An allocator is an object that manages memory allocation in the C++ standard library. The various container data structures used in the C++ standard library, such as lists and sets, require dynamic memory allocation depending on their use. An allocator is an object that defines the functionality needed to manage dynamic memory allocation in a unified way.
Category
- std::allocator:Pool: Memory pooling for the STL Allocator.
Example
#include <memory>
#include <iostream>
#include <string>
int main()
{
std::allocator<int> a1; // default allocator for ints
int* a = a1.allocate(10); // space for 10 ints
a[9] = 7;
std::cout << a[9] << '\n';
a1.deallocate(a, 10);
// default allocator for strings
std::allocator<std::string> a2;
// same, but obtained by rebinding from the type of a1
decltype(a1)::rebind<std::string>::other a2_1;
// same, but obtained by rebinding from the type of a1 via allocator_traits
std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2;
std::string* s = a2.allocate(2); // space for 2 strings
a2.construct(s, "foo");
a2.construct(s + 1, "bar");
std::cout << s[0] << ' ' << s[1] << '\n';
a2.destroy(s);
a2.destroy(s + 1);
a2.deallocate(s, 2);
}
Allocator library
See also
Favorite site
- Wikipedia (en) Allocator (C++)
- cppreference.com: std::allocator
- C++ Standard Allocator, An Introduction and Implementation
- MSDN: allocator::allocate
- Viper Wiki: STL / Allocator
- Allocator requirements and rebind
- Stackoverflow: Why doesn't this C++ STL allocator allocate?
- STL Custom Allocator (kor)