Achieve High Performance By Using The string_view C++17 Feature In C++Builder
In this tutorial, you will learn another modern C++17 feature to work with strings. This feature is a std::string_view. The purpose of any kinds of string reference proposals is to bypass copying data that already owned someplace and of which only a non-mutating representation is required. The std::string_view is one such proposal. There was an earlier one named string_ref.
The std::string_view is a picture of the string and cannot be utilized to alter the original string value. When a std::string_view is constructed, there’s no need to replicate the data. Besides, the std::string_view is smaller than std::string on the heap.
How can you use std::string_view with C++ Builder?
- string_view lives in the
header file
Benefits of the string_view
- string_view is useful when you want to avoid unnecessary duplicates
- The creation of string_view from literals does not need a dynamic allocation.
The following code illustrates how string_view supports save memory by restricting unnecessary dynamic allocations:
#include
#include
#include
#include
#include
// string_view
// Unified way to view a string (memory and length) – without owning it
// No allocation
std::size_t parse(std::string_view str) {
return std::count(str.begin(), str.end(), ‘e’);
}
int _tmain(int argc, _TCHAR *argv[]) {
const std::string str = “hello world”;
const char* c = “Rio de Janeiro”;
std::cout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#ifdef _WIN32 #include #else typedef char _TCHAR; #define _tmain main #endif
#include #include #include #include #include
// string_view // Unified way to view a string (memory and length) – without owning it // No allocation std::size_t parse(std::string_view str) { return std::count(str.begin(), str.end(), ‘e’); }
int _tmain(int argc, _TCHAR *argv[]) { const std::string str = “hello world”; const char* c = “Rio de Janeiro”;
std::cout “Occurrences of letter ‘e’: “ parse(std::string_view(str.data(), str.length())) std::endl; std::cout “Occurrences of letter ‘e’: “ parse(std::string_view(c, strlen(c))) std::endl; system(“pause”); return 0; } |
So, std::string_view is an extraordinary utility for great performance. But, the programmer must assure that std::string_view does not outlive the pointed-to character array.
Additional functions provided by std::string_view can be found here, on the official documentation.
Head over and check out the Windows string_view demo for C++Builder on GitHub.