In C++, std::string::get_allocator() returns a copy of the allocator the string uses to obtain memory.
Everyday code with the default std::allocator<char> almost never needs this. It matters for custom or polymorphic allocators. Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Call with empty brackets when you must propagate an allocator.
C++
auto alloc = s.get_allocator();
std::string t(alloc);
Call
What it does
s.get_allocator()
Returns the string's allocator by value.
When you copy or move strings, allocator behavior follows allocator_traits rules. Custom allocators are an advanced topic.
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 used by the string.
C++ Examples
Example 1 — Basic get_allocator()
Construct another string with the same allocator.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "hi";
auto a = s.get_allocator();
std::string t(a);
t = "ok";
std::cout << t << '\n';
return 0;
}
Output
ok
How It Works
We read the allocator from s.
A new string t is constructed with that allocator.
Assigning text works as usual.
Example 2 — Allocator Equality
Default allocators compare equal.
C++
#include <iostream>
#include <string>
int main() {
std::string a = "A";
std::string b = "B";
std::cout << std::boolalpha
<< (a.get_allocator() == b.get_allocator()) << '\n';
return 0;
}
Output
true
How It Works
Both strings use the default allocator type.
Their allocator values compare equal.
Custom allocators might differ.
Example 3 — Allocator value_type
Remind that the allocator’s value_type is char.
C++
#include <iostream>
#include <string>
#include <type_traits>
int main() {
std::string s;
using A = decltype(s.get_allocator());
std::cout << std::boolalpha
<< std::is_same<A::value_type, char>::value << '\n';
return 0;
}
Output
true
How It Works
We capture the allocator type with decltype.
Its value_type is char for std::string.
That matches how string memory is allocated.
Frequently Asked Questions
A copy of the allocator object the string uses for memory.
Usually no. It matters with custom or pmr allocators.
No. It only returns the allocator object.
Yes, especially with polymorphic memory resources.
It returns a small object and is noexcept for std::string.