使用 stdstring 视图类

Version >= C++ 17

C++ 17 引入了 std::string_view,它只是一个非拥有的 const chars 范围,可以作为一对指针或指针和长度实现。对于需要不可修改的字符串数据的函数,它是一种高级参数类型。在 C++ 17 之前,有三种选择:

void foo(std::string const& s);      // pre-C++17, single argument, could incur
                                     // allocation if caller's data was not in a string
                                     // (e.g. string literal or vector<char> )

void foo(const char* s, size_t len); // pre-C++17, two arguments, have to pass them
                                     // both everywhere

void foo(const char* s);             // pre-C++17, single argument, but need to call
                                     // strlen()

template <class StringT>
void foo(StringT const& s);          // pre-C++17, caller can pass arbitrary char data
                                     // provider, but now foo() has to live in a header

所有这些都可以替换为:

void foo(std::string_view s);        // post-C++17, single argument, tighter coupling
                                     // zero copies regardless of how caller is storing
                                     // the data

请注意,std::string_view 无法修改其基础数据

当你想要避免不必要的副本时,string_view 非常有用。

它提供了 std::string 所具有的功能的有用子集,尽管某些功能表现不同:

std::string str = "lllloooonnnngggg sssstttrrriiinnnggg"; //A really long string

//Bad way - 'string::substr' returns a new string (expensive if the string is long)
std::cout << str.substr(15, 10) << '\n';

//Good way - No copies are created!
std::string_view view = str;

// string_view::substr returns a new string_view
std::cout << view.substr(15, 10) << '\n';