Section

std::basic_string

The class template std::basic_string stores and manipulates sequences of character-like objects, which are non-array objects of TrivialType and StandardLayoutType. Character operations are supplied by the Traits parameter, typically a specialization of std::char_traits.

std::basic_string owns its storage, manages dynamic capacity, and provides a contiguous character sequence suitable for text processing, interoperation with C APIs, and general-purpose string algorithms.

From C++20, member functions of std::basic_string are broadly constexpr, although a std::string object usually cannot persist dynamic storage across constant-evaluation boundaries.

# Declarations

template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
> class basic_string;
namespace pmr {
template<
class CharT,
class Traits = std::char_traits<CharT>
> using basic_string =
std::basic_string<CharT, Traits, std::pmr::polymorphic_allocator<CharT>>;
}

(since C++17)

# Common aliases

TypeDefinition
std::stringstd::basic_string<char>
std::wstringstd::basic_string<wchar_t>
std::u8stringstd::basic_string<char8_t> (since C++20)
std::u16stringstd::basic_string<char16_t> (since C++11)
std::u32stringstd::basic_string<char32_t> (since C++11)
std::pmr::stringstd::pmr::basic_string<char> (since C++17)
std::pmr::wstringstd::pmr::basic_string<wchar_t> (since C++17)
std::pmr::u8stringstd::pmr::basic_string<char8_t> (since C++20)
std::pmr::u16stringstd::pmr::basic_string<char16_t> (since C++17)
std::pmr::u32stringstd::pmr::basic_string<char32_t> (since C++17)

# Template parameters

  • CharT: character type
  • Traits: traits class that defines comparison, assignment, and other character operations
  • Allocator: Allocator type used for internal storage

# Nested types

TypeMeaning
traits_typeTraits
value_typeCharT
allocator_typeAllocator
size_typeunsigned integer type used for sizes and indexes
difference_typesigned integer type used for iterator differences
reference, const_referencereferences to characters
pointer, const_pointerallocator-aware character pointers
iterator, const_iteratorcontiguous iterators over the character sequence
reverse_iterator, const_reverse_iteratorreverse iterators over the character sequence

# Data members

  • npos: special size_type(-1) sentinel used by search and substring operations

# Semantics

  • A basic_string owns a contiguous sequence of characters.
  • The stored sequence is suitable for C interop through c_str() and data(), with the usual null-termination guarantees for string access.
  • Growth, replacement, and insertion operations may reallocate storage and therefore invalidate references, pointers, and iterators.
  • The type models an owning string, unlike basic_string_view, which is non-owning.

# Example

#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';
}

This is the common basic_string pattern: owning contiguous text storage, direct character access, and rich search/substring operations on top of dynamically managed capacity.

# Reference map

AreaKey entries
Construction and lifetimebasic_string::basic_string, basic_string::~basic_string, operator=, assign, assign_range, get_allocator
Element accessat, operator[], front, back, data, c_str, operator basic_string_view
Iteratorsbegin, cbegin, end, cend, rbegin, crbegin, rend, crend
Capacityempty, size, length, max_size, reserve, capacity, shrink_to_fit
Modifiersclear, insert, insert_range, erase, push_back, pop_back, append, append_range, operator+=, replace, replace_with_range, resize, resize_and_overwrite, copy, swap
Search and operationsfind, rfind, find_first_of, find_first_not_of, find_last_of, find_last_not_of, compare, starts_with, ends_with, contains, substr
Non-member functionsoperator+, comparison operators, std::swap(std::basic_string), erase, erase_if, operator«, operator», getline
Numeric conversions and related surfacestoi, stol, stoll, stoul, stoull, stof, stod, stold, to_string, to_wstring, deduction guides, hash, operator"“s

# Iterator invalidation

References, pointers, and iterators to string elements may be invalidated by any standard library operation that takes a non-const reference to the string, such as std::getline, std::swap, or stream extraction, and by calling non-const member functions except operator[], at, data, front, back, begin, rbegin, end, and rend.

# Notes

Although the standard required customized construct/destroy use for std::basic_string element lifetime management until C++23, implementations already used the default mechanism in practice. P1072R10 aligned the wording with that established behavior.

Feature-test macroValueStdFeature
__cpp_lib_string_udls201304LC++14user-defined string literals
__cpp_lib_starts_ends_with201711LC++20starts_with() and ends_with()
__cpp_lib_constexpr_string201907LC++20broader constexpr support for basic_string
__cpp_lib_string_contains202011LC++23contains()
__cpp_lib_containers_ranges202202LC++23range-aware construction and insertion
__cpp_lib_resize_and_overwrite202110LC++23resize_and_overwrite()

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 530C++98contiguity of basic_string storage was accidentally no longer required after LWG 259contiguity required again
LWG 2861C++98value_type was Traits::char_typechanged to CharT
LWG 2994 (P1148R0)C++98behavior was undefined if Traits::char_type or Allocator::value_type differed from CharTprogram is ill-formed in that case

# See also