C++

C++ [Container 4] Strings

std::string_view

Posted by Rico's Nerd Cluster on January 29, 2023

std::string_view

std::string_view is a non-owning view of a character sequence. It doesn’t have dynamic initialization or ctor, and it’s trivially copyable (always 16 bytes that include ptr and length). It can be initialized from string literals during compile time

1
2
constexpr std::string_view str = "hello";
static_assert(str.size() == 14);
  • No lifetime management, no allocation
  • std::string is always null-terminated, but std::string_view not required to be.
  • Usage: std::string_view is read-only.
  • Comparison:
1
std::string_view(m.name) = name;    // name is std::string_view, m.name is std::string