Why Don't You Use String Views Instead of Passing Std:Wstring by Const&

An exploration of why std::wstring_view isn't always a drop-in replacement for const std::wstring&, especially when dealing with Win32 APIs that require null-terminated strings.
…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! So, I won’t do that!
In fact, my C++ code in question talks to some Win32 C-style APIs. These expect PCWSTR as input parameters. 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.
P.S. Invoking data() vs. c_str() – To make things clearer, when you need a null-terminated C-style string pointer, it’s better to invoke the .c_str() method on [w]string. 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












