C ++ 17 std :: basic_string_view invalidate C string usage?

In C ++ 17, std::basic_string_view , which is a non-owned string version, and its class only stores a pointer to the first element of the string and the size of the string. Is there a reason to keep using C strings?

+5
source share
2 answers

Is there a reason to keep using C strings?

I think it would be fair to say that, apart from talking to the C API, there has never been a reason to use C strings.

When designing an interface for a function or method that just needs read-only characters, you need to prefer std::string_view . For instance. string search, uppercase copies, printing, etc.

When designing an interface that takes a copy of a character string, you should probably prefer the first and last iterators. However, std::string_view can be considered as a proxy for these iterators, so string_view is suitable.

If you want to take responsibility for a long string, you probably prefer to skip std::string by value or by r-value reference.

When designing an object that marshals access the c API, which expects null-terminated strings, you should prefer std :: string or std :: string const & - because its c_str () method correctly returns a null-terminated string.

When storing strings in objects (which are not temporary proxies), prefer std :: string.

Of course, using const char* as the data owner in C ++ never works. There is always a better way. This has been true since C ++ 98.

+8
source

Invalidate has a technical meaning here that I consider unintentional. It sounds like this: "obviate" is the intended word.

You still have to create and consume C strings in order to interact with common APIs. For example, POSIX has open and execve , Win32 has approximate equivalents of CreateFile and CreateProcess , and all these functions work on C lines. But in the end, you still call str.data() or str.c_str() to interact with these APIs interfaces, so the use of C strings does not disappear, regardless of whether str std::basic_string_view or std::basic_string .

You still need to understand which C lines are intended for the proper use of these APIs. While std::string guarantees the NUL terminator, std::string_view does not work, and none of them guarantee that there is no NUL byte in the string. You will need to sanitize the NUL bytes in the middle of your string anyway.

This does not even affect the wealth of third-party libraries that use C lines, or the cost of re-equipping native code that uses C lines for one that uses std::string_view .

+6
source

Source: https://habr.com/ru/post/1265944/


All Articles