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>.

These are particularly useful in functions that need to read a string but do not need to modify it. Instead of creating a copy of a string for a function, we can simply view an existing string! Additionally, <string_view> is very flexible, allowing not only C++ style strings to be converted to a string view, but even C-style strings. Below is an example demonstrating a simple usage of std::string_view:

#include <iostream>
#include <string>
#include <string_view>

void printString(std::string_view str) {
std::cout << str << std::endl;
}

int main() {
std::string_view strv{"strv"}; // C++ string_view
printString(strv);

std::string str{"str"}; // C++ string
printString(str);

char cstr[] = "cstr"; // C-style string
printString(cstr);

return 0;
}
Output:

strv
str
cstr

In this example, the printString function takes in a std::string_view as a parameter, which makes this function very lightweight and…

--

--

CMP

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