3

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) {
}

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?

  • 2
    It isn't a view of a `std::string`, but a view of a contiguous sequence of characters. It has most of the the `std::string` interface because that's consistent. – chris Mar 26 '17 at 01:26
  • 2
    `const type&` is the fastest way to provide a view only interface to a class. `string_view` is special because you use it when you *don't have* a `std::string`. – aschepler Mar 26 '17 at 01:40
  • Possible duplicate of [Why string\_view instead of generalized container\_view?](https://stackoverflow.com/questions/39034413/why-string-view-instead-of-generalized-container-viewt) – underscore_d Apr 12 '18 at 14:34

1 Answers1

6

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++ 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.

Darklighter
  • 2,082
  • 1
  • 16
  • 21