Improved string handling in C++20

CMP
3 min readNov 20, 2023

Many C++ programmers are familiar with the basics of the <string> library, particularly the use of std::string when creating a string in C++. This is definitely an improvement over the old C-style “strings” using null-terminated char arrays. However, the C++ standard libray has introduced more useful components in C++17 and C++20 to help you write more effective code in both the <string> and <string_view> library headers.

std::basic_string

In the <string> header, the std::basic_string class is a templated class that provides specializations for various string types, including std::string aka std::basic_string<char> for common strings and std::wstring aka std::basic_string<wchar_t> for wide strings.

There are also fixed-width specific strings like std::u32string aka std::basic_string<char32_t> and std::u16string aka std::basic_string<char16_t>. In C++20, char8_t was added, which also brought along std::u8string aka std::basic_string<char8_t>. I have no idea why it took until C++20 to introduce char8_t when char16_t and char32_t existed in C++11, but at least we have it now!

std::basic_string_view

In C++17, the <string_view> header was added, providing a lightweight read-only alternative to using the string types in the <string> header. These string views are analogous to the previously described strings. For example, the <string_view> equivalent of std::u32string is std::u32string_view aka std::basic_string_view<char32_t>.

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.