为什么只有字符串视图? [英] Why only string view?

查看:53
本文介绍了为什么只有字符串视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 17的字符串视图为开发人员提供了一种方法,可以将便宜的非所有者引用传递给实际上可以是 string_view 是显式的:

C++17's string view gives developers a way to pass around cheap non-owning references to a string that can actually be faster than const std::string&. I might be naive, but this sounds pretty similar to Java's built-in mechanic to copy references of an object. Built-in wrappers like Integer and String are immutable. Java's "reference" mechanic gives you a guarantee that these objects will hold the same value throughout the lifetime of a program. The difference is in C++, string_view is explicit in a program like so:

void retrieve_an_object (string_view sv) {
}

这比Java令人惊讶的(对C ++开发人员而言)机制更具自我记录性.但是对于标准和库编写者来说,为C ++中每个可能的类编写一个视图类无疑是一个巨大的负担.C ++也许可以采用一种更专用的方式将对象标记为仅查看",而不必编写整个类;如果这样,为什么将其从考虑中删除?

This is more self-documenting than Java's surprising (to C++ developers) mechanic. But surely it is a huge burden to the standard and library writers to write a view class for every conceivable class in C++. Could C++ perhaps have a more dedicated way of marking objects as "view only" without having to write an entire class and if so, why has this been removed from consideration?

推荐答案

视图类( string_view array_view )旨在为(只读)访问他们要呈现的对象的一部分.
就像 const& 一样,其中包含有关开头和结尾的其他信息.

The view classes (string_view, array_view) are meant to give (read only) access to parts of the object they are presenting.
It’s like a const & with additional information about a different beginning and end.

C ++有一种专用的方式来仅查看对象: const& .(以及 std :: reference_wrapper< const T> )

C++ has a dedicated way for view only objects: const &. (as well as std::reference_wrapper<const T>)

如果只想访问某些数据结构的特定部分,则需要一个专用的视图类,该类知道应提供哪些部分,这本身并不是真正可以推广的.

If you only want to give access to specific parts of some data structure you need a dedicated view class which knows what parts should be made available, this is not really generalizable per se.

这篇关于为什么只有字符串视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆