What is the C++ String view in C++ 17?
In C++, std::string is the standard way of working with strings as it gives users a lot of convenient functionalities to work with. std::string supports string operations such as searching for substrings, comparing strings, concatenating strings, and slicing strings (among many others).
However, std::string requires space to be dynamically allocated in the buffer and more memory to be dynamically allocated each time an operation is performed on the string.
What is string_view?
Conceptually, string_view is only a view of the string and cannot be used to modify the actual string. When a string_view is created, there’s no need to copy the data (unlike when you create a copy of a string). Furthermore, in terms of size on the heap,string_view is smaller than std::string.
Note:
std::string_viewcannot modify its underlying data and is only available in the C++ 17 version.
Why use std::string_view?
string_viewis useful when you want to avoid unnecessary copies.- String_views are less memory-intensive to construct and copy. The creation of
string_viewfrom literals does not require a dynamic allocation. - Similarly, when creating a substring,
std::string::substrreturns a new string that potentially involves a dynamic allocation. However, we can construct astring_viewfrom the address of a position in our string to make sure that no new memory will be dynamically allocated.
Code
The following code demonstrates how string_view helps save memory by preventing unnecessary dynamic allocations:
#include <iostream>using namespace std;int main() {std::string str = "The quick brown fox jumps over the lazy dog. And then runs away!!!";//'string::substr' returns a new string//this function is memory-intensive, specially if the string is realy longstd::cout << str.substr(5, 15) << '\n';//The creation of string_view from the literals does not//require a dynamic allocation.std::string_view sv = str;// string_view::substr returns a new string_view. No new memory allocatedstd::cout << sv.substr(5, 15) << '\n';}
Other functions supported by string_view can be found here, on the official documentation page.
Free Resources