std::basic_string(3)
π std::basic_string π
okay bestie, this is the std::basic_string(3) page from the C++ Standard Libary manual, and part 1 is lowkey a whole saga. Grab a boba π§, because we're doing the full tour and keeping every single detail. No cap.
πΈ NAME πΈ
std::basic_string - std::basic_string π
(yes, the name is the name, and it's already serving main-character energy).
β¨ Synopsis β¨
Defined in header <string>:
template<
class CharT,
class Traits = std::char_traits<CharT>,
(1)
class Allocator = std::allocator<CharT>
> class basic_string;
namespace pmr {
template<
class CharT,
class Traits = std::char_traits<CharT>
(2) (since C++17)
> using basic_string =
std::basic_string<CharT, Traits,
std::pmr::polymorphic_allocator<CharT>>;
}
The class template basic_string stores and manipulates sequences of character-like objects, which are non-array objects of TrivialType and StandardLayoutType. The class is dependent neither on the character type nor on the nature of operations on that type. The definitions of the operations are supplied via the Traits template parameter - a specialization of std::char_traits or a compatible traits class. It's giving "generic string, but make it standards-lawful."
The elements of a basic_string are stored contiguously, that is, for a basic_string s, &*(s.begin() + n) == &*s.begin() + n for any n in [0, s.size()), and *(s.begin() + s.size()) has value CharT() (a null terminator) (since C++11); or, equivalently, a pointer to s[0] can be passed to functions that expect a pointer to the first element of an array (until C++11) a null-terminated array (since C++11) of CharT.
std::basic_string satisfies the requirements of AllocatorAwareContainer (except that customized construct/destroy are not used for construction/destruction of elements), SequenceContainer and ContiguousContainer (since C++17).
If any of Traits::char_type and Allocator::char_type is different from CharT, the program is ill-formed. Like, ill-formed ill-formed β do not pass go. π
Member functions of std::basic_string are constexpr: it is possible to create and use std::string objects in the evaluation of a constant expression. (since C++20) However, std::string objects generally cannot be constexpr, because any dynamically allocated storage must be released in the same evaluation of constant expression. So close, yet so heap-allocated. π
Several typedefs for common character types are provided:
Defined in header <string>:
std::stringβstd::basic_string<char>std::wstringβstd::basic_string<wchar_t>std::u8string(C++20)βstd::basic_string<char8_t>std::u16string(C++11)βstd::basic_string<char16_t>std::u32string(C++11)βstd::basic_string<char32_t>std::pmr::string(C++17)βstd::pmr::basic_string<char>std::pmr::wstring(C++17)βstd::pmr::basic_string<wchar_t>std::pmr::u8string(C++20)βstd::pmr::basic_string<char8_t>std::pmr::u16string(C++17)βstd::pmr::basic_string<char16_t>std::pmr::u32string(C++17)βstd::pmr::basic_string<char32_t>
π Template parameters π
CharTβ character typeTraitsβ traits class specifying the operations on the character typeAllocatorβ Allocator type used to allocate internal storage
π Member types π
Here's the member-type lineup, no cap:
traits_typeβTraitsvalue_typeβCharTallocator_typeβAllocatorsize_type- until C++11:
Allocator::size_type - since C++11:
std::allocator_traits<Allocator>::size_type
- until C++11:
difference_type- until C++11:
Allocator::difference_type - since C++11:
std::allocator_traits<Allocator>::difference_type
- until C++11:
referenceβvalue_type&const_referenceβconst value_type&pointer- until C++11:
Allocator::pointer - since C++11:
std::allocator_traits<Allocator>::pointer
- until C++11:
const_pointer- until C++11:
Allocator::const_pointer - since C++11:
std::allocator_traits<Allocator>::const_pointer
- until C++11:
iterator- until C++20:
LegacyRandomAccessIteratorandLegacyContiguousIteratortovalue_type - since C++20:
LegacyRandomAccessIterator,contiguous_iterator, andConstexprIteratortovalue_type
- until C++20:
const_iterator- until C++20:
LegacyRandomAccessIteratorandLegacyContiguousIteratortoconst value_type - since C++20:
LegacyRandomAccessIterator,contiguous_iterator, andConstexprIteratortoconst value_type
- until C++20:
reverse_iteratorβstd::reverse_iterator<iterator>const_reverse_iteratorβstd::reverse_iterator<const_iterator>
π¦ Member functions π¦
constructorβ constructs abasic_string(public member function)destructorβ destroys the string, deallocating internal storage if used (public member function)operator=β assigns values to the string (public member function)assignβ assign characters to a string (public member function)assign_range(C++23)β assign a range of characters to a string (public member function)get_allocatorβ returns the associated allocator (public member function)
β¨ Element access β¨
atβ accesses the specified character with bounds checking (public member function)operator[]β accesses the specified character (public member function)front(DR*)β accesses the first character (public member function)back(DR*)β accesses the last character (public member function)dataβ returns a pointer to the first character of a string (public member function)c_strβ returns a non-modifiable standard C character array version of the string (public member function)operator basic_string_view(C++17)β returns a non-modifiablestring_viewinto the entire string (public member function)
π Iterators π
beginβ returns an iterator to the beginning (public member function)cbegin(C++11)β returns an iterator to the beginning (public member function)endβ returns an iterator to the end (public member function)cend(C++11)β returns an iterator to the end (public member function)rbeginβ returns a reverse iterator to the beginning (public member function)crbegin(C++11)β returns a reverse iterator to the beginning (public member function)rendβ returns a reverse iterator to the end (public member function)crend(C++11)β returns a reverse iterator to the end (public member function)
π Capacity π
emptyβ checks whether the string is empty (public member function)sizeβ returns the number of characters (public member function)lengthβ returns the number of characters (public member function)max_sizeβ returns the maximum number of characters (public member function)reserveβ reserves storage (public member function)capacityβ returns the number of characters that can be held in currently allocated storage (public member function)shrink_to_fit(DR*)β reduces memory usage by freeing unused memory (public member function)
π₯ Modifiers π₯
clearβ clears the contents (public member function)insertβ inserts characters (public member function)insert_range(C++23)β inserts a range of characters (public member function)eraseβ removes characters (public member function)push_backβ appends a character to the end (public member function)pop_back(DR*)β removes the last character (public member function)appendβ appends characters to the end (public member function)append_range(C++23)β appends a range of characters to the end (public member function)operator+=β appends characters to the end (public member function)replaceβ replaces specified portion of a string (public member function)replace_with_range(C++23)β replaces specified portion of a string with a range of characters (public member function)copyβ copies characters (public member function)resizeβ changes the number of characters stored (public member function)resize_and_overwrite(C++23)β changes the number of characters stored and possibly overwrites indeterminate contents via user-provided operation (public member function)swapβ swaps the contents (public member function)findβ finds the first occurrence of the given substring (public member function)rfindβ find the last occurrence of a substring (public member function)find_first_ofβ find first occurrence of characters (public member function)find_first_not_ofβ find first absence of characters (public member function)find_last_ofβ find last occurrence of characters (public member function)find_last_not_ofβ find last absence of characters (public member function)
π OPERATIONS π
compareβ compares two strings (public member function)starts_with(C++20) β checks if the string starts with the given prefix (public member function)ends_with(C++20) β checks if the string ends with the given suffix (public member function)contains(C++23) β checks if the string contains the given substring or character (public member function)substrβ returns a substring (public member function)
π CONSTANTS π
npos[static]β special value. The exact meaning depends on the context (public static member constant)
bestie npos is that girl β she's whatever she needs to be depending on the context, lowkey iconic π«Ά
β¨ NON-MEMBER FUNCTIONS β¨
operator+β concatenates two strings or a string and a char (function template)operator==,operator!=,operator<,operator>,operator<=,operator>=β lexicographically compares two strings (function template) β and heads up, these six all got removed in C++20 πoperator<=>(C++20) β lexicographically compares two strings (function template), the shiny new spaceship one, slay πstd::swap(std::basic_string)β specializes thestd::swapalgorithm (function template)erase(std::basic_string)/erase_if(std::basic_string)(C++20) β erases all elements satisfying specific criteria (function template)
π INPUT/OUTPUT π
operator<</operator>>β performs stream input and output on strings (function template)getlineβ read data from an I/O stream into a string (function template)
π§ NUMERIC CONVERSIONS π§
stoi,stol,stoll(C++11) β converts a string to a signed integer (function)stoul,stoull(C++11) β converts a string to an unsigned integer (function)stof,stod,stold(C++11) β converts a string to a floating point value (function)to_string(C++11) β converts an integral or floating-point value to string (function)to_wstring(C++11) β converts an integral or floating-point value towstring(function)
π¦ LITERALS π¦
Defined in inline namespace std::literals::string_literals
operator""s(C++14) β converts a character array literal tobasic_string(function)
π HELPER CLASSES π
std::hash<std::basic_string>(C++11) β hash support for strings (class template specialization)
πΈ Deduction guides (since C++17) πΈ
π NOTES π
Okay so this is a whole thing. Even though it's required that a customized construct or destroy is used when constructing or destroying elements of std::basic_string until C++23, literally all implementations only used the default mechanism. The requirement got corrected by P1072R10 to match existing practice. So like... the standard said one thing and everyone did another and now the standard agrees with the people. periodt π
β Feature-test macro β
__cpp_lib_string_udlsβ value201304L,(C++14)β User-defined literals for string types__cpp_lib_starts_ends_withβ value201711L,(C++20)βstarts_with,ends_with__cpp_lib_constexpr_stringβ value201907L,(C++20)β Constexpr forstd::basic_string__cpp_lib_char8_tβ value201907L,(C++20)βstd::u8string__cpp_lib_erase_ifβ value202002L,(C++20)βerase,erase_if__cpp_lib_string_containsβ value202011L,(C++23)βcontains__cpp_lib_string_resize_and_overwriteβ value202110L,(C++23)βresize_and_overwrite(Member functions for...)__cpp_lib_containers_rangesβ value202202L,(C++23)β construction, insertion, and replacement that accept container compatible range
π₯ EXAMPLE π₯
// Run this code
#include <iostream>
#include <string>
int main()
{
using namespace std::literals;
// Creating a string from const char*
std::string str1 = "hello";
// Creating a string using string literal
auto str2 = "world"s;
// Concatenating strings
std::string str3 = str1 + " " + str2;
// Print out the result
std::cout << str3 << '\n';
std::string::size_type pos = str3.find(" ");
str1 = str3.substr(pos + 1); // the part after the space
str2 = str3.substr(0, pos); // the part till the space
std::cout << str1 << ' ' << str2 << '\n';
// Accessing an element using subscript operator[]
std::cout << str1[0] << '\n';
str1[0] = 'W';
std::cout << str1 << '\n';
}
Output:
hello world
world hello
w
World
no cap that's genuinely a cute little demo, it flexes construction, literals, concatenation, find, substr and subscript access all in like 25 lines π
π DEFECT REPORTS π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
LWG 530β applied to C++98 β as published: contiguity of the storage for elements ofbasic_stringwas accidently made not required byLWG259β correct behavior: required againLWG 2994(P1148R0) β applied to C++98 β as published: the behavior is undefined if any ofTraits::char_type[1] andAllocator::char_typeis different fromCharTβ correct behavior: the program is ill-formed in this case
1. β TheTraits::char_typecase is fixed inP1148R0.
π«Ά SEE ALSO π«Ά
basic_string_view(C++17) β read-only string view (class template)
πΈ EXTERNAL LINKS πΈ
- C++ string handling
Hidden category:
- Pages with unreviewed LWG DR marker π
and that's the whole page bestie, you ate π
β¨ this one's straight from cppreference.com, version 2024.06.10, filed under std::basic_string(3) β go forth and string responsibly, mwah ππ¦π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms