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.
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_view
cannot modify its underlying data and is only available in the C++ 17 version.
std::string_view
?string_view
is useful when you want to avoid unnecessary copies.string_view
from literals does not require a dynamic allocation.std::string::substr
returns a new string that potentially involves a dynamic allocation. However, we can construct a string_view
from the address of a position in our string to make sure that no new memory will be dynamically allocated.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