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 signature print(std::string_view) which can accept C-style strings, std::string and std::string_view.

Note

std::string_view works with constexpr.

References

  1. https://www.learncpp.com/cpp-tutorial/introduction-to-stdstring_view/