Use string views instead of passing std:wstring by const&

While modern C++ often suggests using string views over const references, doing so in Win32 programming can introduce dangerous bugs due to the lack of null-termination guarantees.
…Because (in the given context) that would be **wrong **🙂
This “suggestion” comes up with some frequency…
The context is this: I have some Win32 C++ code that takes input string parameters as const std::wstring&, and someone suggests me to substitute those wstring const reference parameters with * string views *like std::wstring_view. This is usually because they have learned from someone in some course/video course/YouTube video/whatever that in “modern” C++ code you should use string views instead of passing string objects via const&.
[Sarcastic mode on] Are you passing a string via const&? Your code is not modern C++! You are such an ignorant C++98 old-style C++ programmer! [Sarcastic mode off] 😉
So, thank you for the suggestion, but using std::wstring_view instead of const std::wstring& in that context would introduce nasty bugs in my C++ code! In fact, my C++ code in question talks to some Win32 C-style APIs. These expect PCWSTR as input parameters representing Unicode UTF-16 strings. A PCWSTR is basically a typedef for a Null_terminated const wchar_t*. The key here is the null termination part.
std::wstring guarantees that the pointer returned by the data() method points to a null-terminated string. On the other hand, invoking std::wstring_view::data() does not guarantee that the returned pointer points to a null-terminated string. It may, or may not. But there is no guarantee!
So, since [w]string_views are not guaranteed to be null-terminated, using them with Win32 APIs that expect null-terminated strings is totally wrong and a source of nasty bugs. If your target are Win32 API calls that expect null-terminated C-style strings, just keep passing good old std::wstring by const&.
P.S. Invoking data() vs. c_str() – To make things clearer and more bug-resistant, when you need a null-terminated C-style string pointer, it’s better to invoke the c_str() method on [w]string. In this way, if someone tries to “modernize” the code to [w]string_view, they get a compiler error because string views don't have a c_str() method. It’s much better to get a compile-time error than a subtle run-time bug!
Source: Hacker News












