June 21st, 2024

The Windows Runtime winrt::hstring and the C++ std::wstring are inter-assignable

For the past few days, I’ve been talking about converting between various string types while avoiding data loss and security issues if an embedded null is present. But in the case where you are dealing with winrt::hstring and std::wstring, the story is much simpler.

The winrt::hstring and std::wstring types can simply be assigned to each other. No need to do funny wstring_view or c_str() nonsense.

winrt::hstring h;
std::wstring s;

h = s; // this works!
s = h; // this also works!

The assignments work because winrt::hstring and std::wstring both support assignment from std::wstring_view, and both winrt::hstring and std::wstring are convertible to std::wstring_view.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

1 comment

Discussion is closed. Login to edit/delete existing comments.

Newest
Newest
Popular
Oldest
  • Neil Rashbrook

    So what you’re saying is that two of each of yesterday’s function bodies could have been return s; or return v; as appropriate?

Feedback