What is the difference between "string_view" and "string" and which one should prefer?

Asked

Viewed 75 times

2

What is the difference of the new class of C++17 string_view to the string?

In which situations is indicated the use of string_view instead of string?

1 answer

2


To string_view is a simple reference to a string. The latter has an object with the data which is a string of characters. The former has a pointer to the string and how many characters are your size.

The pointer does not need to be for the first character and quantity does not need to catch all of the following characters. So it is a form of substring but does not copy the data to another object, and does not take ownership of the original object. It is a way to keep access more efficient.

The object string_view does not allow you to make changes to the object it references, so it is considered immutable and has no competition problems.

Whenever you need to make a reference to the object string or part of it without needing to change it or have something separate it is more interesting.

Did some tests:

Substr com view é muito mais rápido ~20X

But it depends on implementation. See that depending on the compiler the same operation of split can be better or worse. The former uses GCC and the latter uses Clang.

Com Split é um pouco mais lento

Mas não no Clang

Documentation.

  • 1

    About this part: The string_view object does not allow you to make changes to the object it references, so it is considered immutable and has no competition problems. So string_view is like a const string? Another thing, there are several fonts on the internet saying that string_view does not use dynamic allocation, as this is possible?

  • It is because, as already said, the allocated memory belongs to another object, the verdaderua string. I can’t guarantee what the actual implementation looks like, but I imagine the string_view as a simple char pointer* accompanied by an int indicating the number of characters.

  • You can see it as const string, although it is less than this. If you pay attention I said that it is only a pointer and a size, why only for this? Save in the variable itself, it is small size, known, fixed, has no problems of slashing, does not need inheritance, nothing. And as @Marcus spoke the likely implementation (nothing in the specification requires it to be so).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.