什么是string_view?

什么是string_view?

问题描述:

string_view 是C ++库基础TS( N3921 )添加到C ++ 17

string_view was a proposed feature within the C++ Library Fundamentals TS(N3921) added to C++17

据我所知是表示某种类型的字符串概念的类型,它是可以存储可作为字符串查看的任何类型容器的视图。

As far as i understand it is a type that represent some kind of string "concept" that is a view of any type of container that could store something viewable as a string.


  • 这是对的吗?

  • 应将规范的
    const std :: string& 参数类型变成 string_view

  • 关于 string_view 的另一个要点是否值得考虑?

  • Is this right ?
  • Should the canonical const std::string& parameter type become string_view ?
  • Is there another important point about string_view to take into consideration ?

任何种类的字符串引用和数组引用建议的目的都是为了避免复制已经存在的数据在其他地方拥有,并且只需要一个不变的视图即可。有争议的 string_view 是这样的建议之一;还有更早的版本,分别是 string_ref array_ref

The purpose of any and all kinds of "string reference" and "array reference" proposals is to avoid copying data which is already owned somewhere else and of which only a non-mutating view is required. The string_view in question is one such proposal; there were earlier ones called string_ref and array_ref, too.

想法始终是存储一对指向第一个元素的指针和一些现有数据数组或字符串的大小。

The idea is always to store a pair of pointer-to-first-element and size of some existing data array or string.

这样的视图句柄类可以按值便宜地传递,并且可以提供便宜的子字符串操作(可以通过简单的指针增量和大小调整来实现)。

Such a view-handle class could be passed around cheaply by value and would offer cheap substringing operations (which can be implemented as simple pointer increments and size adjustments).

许多用法的字符串不需要实际拥有字符串,并且所讨论的字符串通常已经由其他人拥有。因此,通过避免不必要的复制(考虑所有可以节省的分配和异常),确实有提高效率的潜力。

Many uses of strings don't require actual owning of the strings, and the string in question will often already be owned by someone else. So there is a genuine potential for increasing the efficiency by avoiding unneeded copies (think of all the allocations and exceptions you can save).

原始的C字符串遭受了问题是null终止符是字符串API的一部分,因此您不更改基础字符串就很难创建子字符串(la strtok )。在C ++中,可以通过分别存储长度并将指针和大小包装到一个类中来轻松解决。

The original C strings were suffering from the problem that the null terminator was part of the string APIs, and so you couldn't easily create substrings without mutating the underlying string (a la strtok). In C++, this is easily solved by storing the length separately and wrapping the pointer and the size into one class.

这是与C ++标准库哲学不同的一个主要障碍和差异。我可以想到的是,此类引用视图类与其他标准库具有完全不同的所有权语义。基本上,标准库中的所有其他内容都是无条件安全和正确的(如果可以编译,则是正确的)。对于此类参考类,这不再是事实。程序的正确性取决于使用这些类的环境代码。因此,这更难检查和教导。

The one major obstacle and divergence from the C++ standard library philosophy that I can think of is that such "referential view" classes have completely different ownership semantics from the rest of the standard library. Basically, everything else in the standard library is unconditionally safe and correct (if it compiles, it's correct). With reference classes like this, that's no longer true. The correctness of your program depends on the ambient code that uses these classes. So that's harder to check and to teach.