DEV Community

hacking C++
hacking C++

Posted on

std::string C++20/23 Interface Novelties

Here's a small cheat sheet for 4 new member functions of std::string.

cheat sheet showing new member functions of std::string introduced with C++20 and C++23: starts_with, ends_with, containts and resize_and_overwrite

More Cheat Sheets


resize_and_overwrite avoids costly initialization of a string's memory buffer if you need to immediatly overwrite it with characters coming from e.g., a call to a C API.

std::string s1;
s1.resize(1024);  // costly initialization
// write characters to string:
size_t sizeWritten = some_C_library(, s1.size());

std::string s2;
s2.resize_and_overwrite(1024, [](char* p, size_t n){
  size_t sizeWritten = some_C_library(p, n);
  return sizeWritten;

Enter fullscreen mode Exit fullscreen mode

Function Signatures and Overloads

namespace std {
template <typename CharT, typename Traits, typename Allocator>
class basic_string {
  // ...
  bool contains (std::basic_string_view<CharT>);
  bool contains (CharT);
  bool contains (CharT const*);

  bool starts_with (std::basic_string_view<CharT>);
  bool starts_with (CharT);
  bool starts_with (CharT const*);

  bool ends_with (std::basic_string_view<CharT>); 
  bool ends_with (CharT); 
  bool ends_with (CharT const*);

  template <typename Operation>
  constexpr void resize_and_overwrite (size_type count, Operation op);
  // ...
}  // std
Enter fullscreen mode Exit fullscreen mode

Top comments (0)