CKTIS / C++
std::pmr::string — a string with a polymorphic allocator
std::pmr::string is a std::basic_string specialization using std::pmr::polymorphic_allocator<char>. It lets you select a memory resource at runtime without changing the string's type.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <string>
#include <memory_resource>
// Equivalent underlying type:
// std::basic_string<char, std::char_traits<char>, std::pmr::polymorphic_allocator<char>>
std::pmr::string text{&resource};std::pmr::string, declared in <string>, is an alias for std::basic_string<char, std::char_traits<char>, std::pmr::polymorphic_allocator<char>>. It provides string operations such as append() and size(), but is a different type from std::string, which uses std::allocator<char>.
To configure a resource, include <memory_resource> and pass a resource pointer when constructing the string. The allocator directs memory requests to that resource. A default-constructed allocator uses the resource returned by std::pmr::get_default_resource(). By contrast, move construction without an allocator argument preserves the source string's allocator and can therefore retain a non-default resource. Using std::pmr::string alone guarantees neither freedom from heap allocation nor a particular allocation count.
The string does not own its resource. The resource must remain available for as long as the string may use it, including during destruction. In the example, resource is constructed before text, so it is destroyed afterward. std::pmr::monotonic_buffer_resource releases accumulated memory collectively; individual deallocations do nothing. Do not call release() while a live string still uses the allocated memory.
The example creates 40 characters, appends !, and prints the length and the result of checking resource identity. The expected output is 41 followed by true, on separate lines. The displayed code was compiled unchanged with a C++23 flag and run in an isolated environment, and its standard output (stdout) was checked for an exact match against the expected output. This does not establish production-runtime support. The linked working draft is maintained rather than frozen as C++23.
Examples
#include <iostream>
#include <memory_resource>
#include <string>
int main() {
std::pmr::monotonic_buffer_resource resource;
std::pmr::string text(40, 'x', &resource);
text.append("!");
std::cout << text.size() << '\n';
std::cout << std::boolalpha
<< (text.get_allocator().resource() == &resource)
<< '\n';
}
Result
41 true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.