7 Eylül 2020 Pazartesi

std::string_view Sınıfı - const char* Veriysi std::string Gibi Kullanmak İçin

Giriş
Şu satırı dahil ederiz.
#include <string_view>
Şu satırı dahil ederiz.
#include <experimental/string_view>
Açıklaması şöyle
The string_view is a wrapper around a const char* which doens't waste memory as it stores only a pointer to the contents, which is not the case for a normal std::string which is designed to be mutable.
C++17 ile geliyor. Bu sınıfın boost'taki karşılığı boost::string_ref

String Literal'dan Kullanma
Şöyle yaparız. Burada "..."sv kullanımı önemli.
using namespace std::literals;

// ... 

auto t1 = std::make_tuple("one"sv, "two"sv, "three"sv);
auto t2 = std::make_tuple("one"sv, "two"sv, "three"sv);
Constructor - std::string
Şöyle yaparız.
std::string str = "Hello world";
std::experimental::string_view v (str);
begin metodu
Şöyle yaparız.
const char* sep = "";
for (auto ch : std::string_view(...))
{
  std::cout << sep << ch;
  sep = " ";
}
data metodu
Şöyle yaparız.
#include <string_view>
void foo(const char* cstr) {}
void bar(std::string_view str){
    foo(str.data ());
}
operator << metodu
Şöyle yaparız.
std::cout << "string view, " << v << "!\n";
substr metodu
Örnek
Şöyle yaparız.
auto sub_v = v.substr(1, 4); // creates a new string_view
std::cout << "sub view, " << sub_v << '\n';
Örnek
Şöyle yaparız.
std::string s = "hello world!";
std::string_view v = s;
v = v.substr(6, 5); // "world"
Diğer
1. std::string_view Null Terminated String Garanti Etmez
Açıklaması şöyle
However, in many of the threads that I have read on the subject of when and where to use std::string_view instead of const std::string &. I have seen many answers say, "When you don't need a null terminated string."

2. std::string_view nesnesini std::string'e  Çevirme
Örnek
static_cast<std::string>(string_view) çağrısı ile yeni bir std::string yaratılır. Şöyle yaparız.
std::string str{"0123456789"};
std::string_view sv(str.c_str(), 5);

std::cout << sv << std::endl;
std::cout << static_cast<std::string>(sv) << std::endl;
std::cout << strlen(static_cast<std::string>(sv).c_str()) << std::endl;
3. std::string nesnesini std::string_view'a Çevirme
std::string nesnesi std::string_view'a çevrilebiliyor ve bu tehlikeli kodlara sebep olabliyor.

Örnek
Şu kullanım yanlış, Çünkü string.substr() metodu geçici bir std::string döndürür ve bu nesne silinir.
std::string s = "hello world!";
std::string_view v(s.substr(6, 5)); // OOPS!
Örnek
Elimizde şöyle bir kod olsun
std::string_view sub_string(
  std::string_view s, 
  std::size_t p, 
  std::size_t n = std::string_view::npos)
{
  return s.substr(p, n);
}
Bu metodu şöyle çağırabiliriz.
using namespace std::literals;

auto source = "foobar"s;

// this is fine and elegant...
auto bar = sub_string(source, 3);
Ancak geçici bir std::string ile de çağrılabilir ve bu kod hatalı olur
// but uh-oh...
bar = sub_string("foobar"s, 3);

Hiç yorum yok:

Yorum Gönder