std::basic_string(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– 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 type
  • Traits β€” traits class specifying the operations on the character type
  • Allocator β€” Allocator type used to allocate internal storage

πŸŽ€ Member types πŸŽ€

Here's the member-type lineup, no cap:

  • traits_type β€” Traits
  • value_type β€” CharT
  • allocator_type β€” Allocator
  • size_type
    • until C++11: Allocator::size_type
    • since C++11: std::allocator_traits<Allocator>::size_type
  • difference_type
    • until C++11: Allocator::difference_type
    • since C++11: std::allocator_traits<Allocator>::difference_type
  • reference β€” value_type&
  • const_reference β€” const value_type&
  • pointer
    • until C++11: Allocator::pointer
    • since C++11: std::allocator_traits<Allocator>::pointer
  • const_pointer
    • until C++11: Allocator::const_pointer
    • since C++11: std::allocator_traits<Allocator>::const_pointer
  • iterator
    • until C++20: LegacyRandomAccessIterator and LegacyContiguousIterator to value_type
    • since C++20: LegacyRandomAccessIterator, contiguous_iterator, and ConstexprIterator to value_type
  • const_iterator
    • until C++20: LegacyRandomAccessIterator and LegacyContiguousIterator to const value_type
    • since C++20: LegacyRandomAccessIterator, contiguous_iterator, and ConstexprIterator to const value_type
  • reverse_iterator β€” std::reverse_iterator<iterator>
  • const_reverse_iterator β€” std::reverse_iterator<const_iterator>

πŸ¦‹ Member functions πŸ¦‹

  • constructor β€” constructs a basic_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-modifiable string_view into 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 the std::swap algorithm (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 to wstring (function)

πŸ¦‹ LITERALS πŸ¦‹

Defined in inline namespace std::literals::string_literals

  • operator""s (C++14) β€” converts a character array literal to basic_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 β€” value 201304L, (C++14) β€” User-defined literals for string types
  • __cpp_lib_starts_ends_with β€” value 201711L, (C++20) β€” starts_with, ends_with
  • __cpp_lib_constexpr_string β€” value 201907L, (C++20) β€” Constexpr for std::basic_string
  • __cpp_lib_char8_t β€” value 201907L, (C++20) β€” std::u8string
  • __cpp_lib_erase_if β€” value 202002L, (C++20) β€” erase, erase_if
  • __cpp_lib_string_contains β€” value 202011L, (C++23) β€” contains
  • __cpp_lib_string_resize_and_overwrite β€” value 202110L, (C++23) β€” resize_and_overwrite (Member functions for...)
  • __cpp_lib_containers_ranges β€” value 202202L, (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 of basic_string was accidently made not required by LWG259 β€” correct behavior: required again
  • LWG 2994 (P1148R0) β€” applied to C++98 β€” as published: the behavior is undefined if any of Traits::char_type[1] and Allocator::char_type is different from CharT β€” correct behavior: the program is ill-formed in this case
1. ↑ The Traits::char_type case is fixed in P1148R0.

🫢 SEE ALSO 🫢

  • basic_string_view (C++17) β€” read-only string view (class template)

  • 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