Is Platform::String really so useless?

不想你离开。 提交于 2019-11-30 16:49:40

问题


I am trying to write a few lines of code in C++/CX in a "Windows Store" (aka Metro Style) application, and I am surprised to see that Platform::String is missing many basic string operations like "replace" or "index of".

I suppose I could use the internal data, pass it to a std:string instance and apply the operations I need, but I would like to know if I am missing some "Platform::* only" way of doing these operations.

Please note this question is about C++/CX, not C#.


回答1:


The Windows Runtime string type, HSTRING is immutable and is reference counted.

The Platform::String type in C++/CX is simply a wrapper around the HSTRING type and the handful of operations that it supports (see the functions that start with Windows in the Windows Runtime C++ Functions list).

There are no operations that mutate the string because the string type is immutable (hence why there is no Replace). There are a few non-mutating operations (certainly fewer than C++'s std::wstring).

Platform::String does provide Begin() and End() member functions (and non-member begin() and end() overloads) that return random access iterators into the string (they return pointers, wchar_t const*, and pointers are valid random access iterators). You can use these iterators with any of the C++ Standard Library algorithms that take random access iterators and do not attempt to mutate the underlying sequence. For example, consider using std::find to find the index of the first occurrence of a character.

If you need to mutate a string, use std::wstring or std::vector<wchar_t>. Ideally, consider using the C++ std::wstring as much as possible in your program and only use the C++/CX Platform::String where you need to interoperate with other Windows Runtime components (i.e., across the ABI boundary).




回答2:


That is because it isn't intended to be a std::string replacement. From the docs:

The Platform::String Class provides methods for several common string operations, but it's not designed to be a full-featured string class. In your C++ module, use standard C++ string types such as wstring for any significant text processing, and then convert the final result to Platform::String^ before you pass it to or from a public interface.

http://msdn.microsoft.com/en-us/library/windows/apps/hh699879.aspx

So the bottom line is: use std::wstring like you were used to in C++ and only convert to Platform::String when needed.

I think that it is probably better that way, because Platform::String has some pretty confusing semantics (for example nullptr and the empty string are the same thing, so ref new String() == nullptr is true).



来源:https://stackoverflow.com/questions/12533883/is-platformstring-really-so-useless

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!