In C++, std::unordered_set::get_allocator() returns a copy of the allocator the unordered_set uses to get memory for its nodes. Every container has an allocator that it uses for this job.
Most programs never touch it. The default is std::allocator<T> (with the element type of the unordered_set). It is useful in generic code, or when you use a custom memory pool. Include <unordered_set> to use it.
This is a member of std::unordered_set<T>, a hash table of unique values. Find, insert, and erase are usually average constant time. Unlike std::set, values are not sorted and iteration order is unspecified. Elements are const, so you cannot change a stored value through an iterator. There is no operator[] and no at(). Prefer find() or contains() to look up a value, and call reserve() before many inserts.
Syntax
Call get_allocator with empty brackets.
C++
auto alloc = s.get_allocator(); // copy of the allocator
// alloc.allocate(1) / alloc.deallocate(p, 1)
Call
What it does
s.get_allocator()
Returns a copy of the allocator of the unordered_set, as allocator_type.
You get a copy, not the unordered_set's own object. Two default std::allocator objects always compare equal, so memory from one can be released by the other.
Library declarations
C++
allocator_type get_allocator() const noexcept;
Parameters
Parameter
Description
None
get_allocator() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
allocator_type
A copy of the allocator. By default std::allocator<T> for the element type.
C++ Examples
Example 1 — get_allocator() Returns a std::allocator
Check at compile time that the default allocator type is what you expect.
C++
#include <iostream>
#include <memory>
#include <unordered_set>
#include <type_traits>
int main() {
std::unordered_set<int> s;
using Expected = std::allocator<int>;
bool same = std::is_same<decltype(s.get_allocator()), Expected>::value;
std::cout << std::boolalpha;
std::cout << "default allocator: " << same << '\n';
return 0;
}
Output
default allocator: true
How It Works
An unordered_set of int stores int elements, so its default allocator allocates that type.
decltype(s.get_allocator()) gives the type of the returned object. std::is_same compares it with Expected.
They are the same, so true is printed. Nothing was allocated by this program except what the empty unordered_set needs.