就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引起辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the help center为指导。
8 年前关闭。
关于跨平台 Unicode 字符串使用的主题有无数的讨论线程,但似乎存在广泛的意见,但没有解决在我正在从事的特定项目中一直困扰我的一些具体问题:
我有一个大型跨平台 C++ 代码库,可以追溯到近 20 年前。它包含各种字符串实现的大杂烩,包括:
char*
std::string
CFString
该代码库正在被重写以完全使用 Unicode 字符串并实现强大的 MVC 架构,希望该模型将是完全可移植的(Mac OS/IOS/Android/Windows 7 & 8/Unix)。
虽然持久数据被编写为 XML/UTF-8,但在运行时对象中的字符串使用方面存在一些困境:
CFStringCreateWithCharactersNoCopy
或 CFStringCreateMutableWithExternalCharactersNoCopy
)让我自己的类创建 CFStrings 将是一个很好的策略。似乎这可以减少 CFString 在从模型中获取数据后通常需要的转换/分配量——尽管也许在适当的 MVC 实现中, Controller / View 不应该访问模型拥有的实际字符串? 我猜这些问题早就应该解决了——但是从查看这个网站(和其他网站)上的回复我看不出它已经解决了。
最佳答案
I'd like to create a class that cleanly hides the implementation of storage, allocation and common string operations. Through the miracle of C++ operator and assignment overloading I'm hoping to be able to substitute a class instance to replace all the different string parameters that functions can accept. This would allow for an incremental conversion of the code base.
听起来像
std::string
向 const char*
添加强制转换运算符,因此您无需调用 c_str()
.这意味着您必须使用 char
和 UTF-8 用于存储,而不是 UTF-16 或类似的。We are constantly scanning / parsing / analyzing strings, and I worry that using a strictly UTF-8 underlying implementation for persistent objects might have performance issues. If not, would the modern
std::string
found in Microsoft's VC++ and GNU's G++ be a simple underlying implementation?
这取决于其他几个因素。一方面,如果您的输入包含大量非 ascii 数据并且您必须一次分析一个代码点,则 UTF-8 可能效率低下。在这种情况下,UTF-16 甚至 UTF-32 可能更合理,因为从多个字符串元素重新组合代码点时不会有太多的大小写差异。另一方面,性能在很大程度上取决于您是否可以通过引用传递字符串或必须创建拷贝,尤其是在调用函数时。因此,可能需要对现有代码库进行一些修改,以避免复制过多。
The Mac OS / IOS versions ultimately need to have their strings "converted" to CFString. The CF functions are rich and highly optimized. I'm thinking it would be a good strategy to have my own class create CFStrings by providing CF with a buffer (for example, CFStringCreateWithCharactersNoCopy or CFStringCreateMutableWithExternalCharactersNoCopy). Seems as if this could reduce the amount of conversion/allocation CFString would normally require after fetching data from the model — ALTHOUGH perhaps in a proper MVC implementation the Controller/View shouldn't have access to actual strings owned by the model?
当您在不复制数据缓冲区的情况下创建字符串时,您必须确保只要访问该字符串,缓冲区就一直存在。这在某些情况下可能是正确的,但并非在所有情况下都是如此。一般来说,这些问题与您在
char*
中遇到的问题非常相似。由 std::string
支持,这就是为什么c_str()
的原因是一个显式的函数调用,而不仅仅是一个自动转换。通过进行这样的转换,您必须保证原始对象保持分配状态。一般来说,我会通过 const std::string&
View ,因此它们不会意外更改模型拥有的字符串。如果他们需要保留或修改字符串,则必须复制它。Does C++ 11 change the picture for any of these cross-platform string issues?
C++ 11 提供了许多新的智能指针实现,允许您更好地控制字符串对象保持分配的时间。例如,您可以使用
shared_prt<string>
作为你的类的数据存储,获得自动引用计数和字符串释放。这将为您提供更高级别的抽象,但可能与您当前代码库的功能相距甚远,因此我不确定这是否会让您更轻松地进行移植。
关于c++ - 什么是跨平台字符串类的 "Best Practices"以实现良好的模型可移植性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14189864/