HeadlinesBriefing favicon HeadlinesBriefing.com

String Views vs Const References: Win32 API Bug Trap

Hacker News •
×

A developer explains why replacing const std::wstring& parameters with std::wstring_view in Win32 C++ code causes subtle bugs. The issue arises when passing strings to Windows APIs that expect null-terminated UTF-16 strings. While modern C++ courses often recommend string views for performance, this advice doesn't apply universally.

std::wstring guarantees null termination through its data() method, making it safe for Win32 APIs expecting PCWSTR parameters. std::wstring_view offers no such guarantee - the underlying data may or may not be null-terminated. This creates a critical mismatch when interfacing with Windows API functions that require null-terminated C-style strings as input parameters.

The author recommends sticking with const std::wstring& for Win32 interop and using c_str() instead of data() when passing to Windows APIs. This approach prevents accidental bugs if someone later tries to "modernize" the code by switching to string views. The compiler will catch attempts to call c_str() on a string view, which doesn't have that method, preventing runtime errors.