Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++17 std::basic_string_view invalidates the use of C strings?

Tags:

c++

c

c++17

C++17 is introducing std::basic_string_view which is non-owning string version with its class storing only a pointer to the first element of a string and size of the string. Is there still a reason to keep using C strings?

like image 476
Amani Avatar asked Mar 27 '17 07:03

Amani


2 Answers

Is there still a reason to keep using C strings?

I think it would be fair to say that other than speaking to a C API, there has never been a reason to use C strings.

When designing an interface of a function or method that simply needs a read-only representation of characters, you will want to prefer std::string_view. E.g. searching a string, producing an upper-case copy, printing it, and so on.

When designing an interface that takes a copy of a string of characters, you should probably prefer first and last iterators. However, std::string_view could be thought of as a proxy for these iterators, so string_view is appropriate.

If you want to take ownership of a long string, probably prefer to pass std::string, either by value or by r-value reference.

When designing an object that marshals calls to a c API that is expecting null-terminated strings, you should prefer std::string or std::string const& - because its c_str() method will correctly yield a null-terminated string.

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

Of course the use of const char* as an owner of data in c++ is never appropriate. There is always a better way. This has been true since c++98.

like image 139
Richard Hodges Avatar answered Oct 27 '22 00:10

Richard Hodges


"Invalidate" has a technical meaning here which I think is unintentional. It sounds like "obviate" is the intended word.

You are still going to have to produce and consume C strings in order to interact with common APIs. For example, POSIX has open and execve, Win32 has the rough equivalents CreateFile and CreateProcess, and all of these functions operate on C strings. But in the end, you are still calling str.data() or str.c_str() in order to interact with these APIs, so that use of C strings is not going away, no matter whether str is a std::basic_string_view or std::basic_string.

You will still have to understand what C strings are in order to correctly use these APIs. While std::string guarantees a NUL terminator, std::string_view does not, and neither structure guarantees that there is no NUL byte somewhere inside the string. You will have to sanitize NUL bytes in the middle of your string in either case.

This does not even touch on the wealth of 3rd party libraries which use C strings, or the cost of retrofitting your own code which uses C strings to one which uses std::string_view.

like image 41
Dietrich Epp Avatar answered Oct 26 '22 23:10

Dietrich Epp