Skip to content
Tech News
← Back to articles

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

read original get C String View Adapter → more articles
Why This Matters

This article highlights the importance of understanding context when choosing between std::wstring and std::wstring_view in C++. While string views are often recommended for modern C++ code, they can introduce bugs when interfacing with APIs that require null-terminated strings, such as Win32 functions. Recognizing these nuances ensures safer and more reliable code, especially in systems programming and API integrations.

Key Takeaways

Thank you for the suggestion. But *in that context* that would cause nasty bugs in my code, and in code that relies on it.

…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] 😉

(There are also other “gurus” who say that in modern C++ you should always use exceptions to communicate error conditions. Yeah… Well, that’s a story for another time…)

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 (and in other people’s code that relies on my own code)! So, I won’t do that!

In fact, my C++ code in question (like WinReg) 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.

If you have:

// Input string passed via const&. // // Someone suggests me to replace 'const wstring &' // with wstring_view: // // void DoSomething(std::wstring_view s, ...) // void DoSomething(const std::wstring& s, ...) { // This API expects input string as PCWSTR, // i.e. _null-terminated_ const wchar_t*. SomeWin32Api(s.data(), ...); // <-- See the P.S. later }

std::wstring guarantees that the pointer returned by the wstring::data() method points to a null-terminated string.

... continue reading