In C++, std::list::get_allocator() returns a copy of the allocator that the std::list uses to get memory for its nodes. An allocator is a small helper object that creates and frees memory.
Most programs use the default std::allocator and never need this function. It matters for custom allocators and for generic code. Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call get_allocator with empty brackets. It returns the allocator by value.
C++
std::allocator<int> a = l.get_allocator();
int* p = a.allocate(2); // raw memory for two ints
a.deallocate(p, 2); // give it back
Call
What it does
l.get_allocator()
Returns a copy of the allocator object, of type allocator_type.
The returned allocator creates memory for int. The list itself rebinds it internally to build its own nodes.
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. For a plain std::list<int> this is std::allocator<int>.
C++ Examples
Example 1 — get_allocator() to Get Raw Memory
Take the allocator out of a list, allocate room for two ints with it, and give the memory back.
decltype(l.get_allocator()) gives the type that the function returns, without calling it.
std::is_same compares that type with std::allocator<int> at compile time.
A list without a custom allocator uses the default, so ::value is true.
Frequently Asked Questions
A copy of the allocator object that the list uses to create and free its nodes. By default it is std::allocator<T>.
Rarely. It is useful when you use a custom allocator, or when you write generic code that must create objects with the same allocator as a container.
An allocator is a helper object that gets and frees raw memory for a container. Containers such as std::list use it every time they create or destroy a node.
No. You get a copy. The list keeps using its own allocator.
splice() moves nodes between lists. This is only safe if the memory from one list may be freed by the other, which is the case when both allocators compare equal.