有建议可以补充string_view
即将发布的标准中的 C++。
A string_view
是字符上的非拥有可迭代范围,具有您期望的字符串类的许多实用程序和属性,但您不能插入/删除字符(并且在某些子类型中编辑字符通常被阻止)。
我建议尝试这种方法——编写您自己的方法(在您自己的实用程序命名空间中)。 (无论如何,您应该拥有自己的实用程序命名空间,用于可重用的代码片段)。
核心数据是一对char*
pr std::string::iterator
s (or const
版本)。如果用户需要一个空终止的缓冲区,to_string
方法分配一个。我将从不可变(const
) 字符数据。不要忘记begin
and end
:这使得你的视图可以迭代for(:)
loops.
这个设计有一个危险,那就是原来的设计std::string
必须坚持足够长的时间才能比所有观点更持久。
如果您愿意为了安全而放弃一些性能,请拥有一个视图std::shared_ptr<const std::string>
它可以移动一个std::string
进入,第一步将整个缓冲区移入其中,然后开始对其进行切割/解析。 (子视图创建一个指向相同数据的新共享指针)。那么你的视图类更像是一个具有共享存储的不可变字符串。
的好处shared_ptr<const>
版本包括安全性、更长的视图生命周期(不再有生命周期依赖性),并且您可以轻松转发您的const
“substring”类型方法std::string
所以你可以编写更少的代码。
Downsides include possible incompatibility with incoming standard one1, and lower performance because you are dragging a shared_ptr
around.
我怀疑随着语言即将到来和最近的改进,视图和范围在现代 C++ 中将变得越来越重要。
boost::string_ref http://www.boost.org/doc/libs/1_55_0/libs/utility/doc/html/string_ref.html显然是 C++1y 标准提案的实现。
1 however, given how simple it is to add capabilities in template metaprogramming, having a "resource owner" template argument to a view type might be a good design decision. Then you can have owning and non-owning string_view
s with otherwise identical semantics...