std::string_view provides read-only access to a string value. Unlike std::string, initializing a std::string_view variable does not copy value to the variable but creates a view to the value.
#include <string_view>
#include "../helpers/stdout.h"
#include <iostream>
int main(int argc, char const *argv[])
{
std::string_view name{"John Doe"};
print(name);
return 0;
}The cool thing is that the initializer value can be a C-style string, std::string, and std::string_view. So, if a function works on a readonly string, we can make its parameter of type std::string_view that should accept string of any type mentioned here.
Note
print()has signatureprint(std::string_view)which can accept C-style strings,std::stringandstd::string_view.
Note
std::string_viewworks withconstexpr.