Delphi XE4不变字符串

前端之家收集整理的这篇文章主要介绍了Delphi XE4不变字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用Delphi XE4 for iOS平台,引入了一种新的字符串类型:不变的基于零的字符串。到目前为止,Delphi已经写入了可变字符串。所以问题是,这对我未来的编程意味着什么?一个字符串类型有其他优点吗?当切换到新的字符串类型(除了明显的0对1基数之外)需要处理什么陷阱?

解决方法

根据 Marco Cantù’s whitepaper,XE4 iOS目标中的字符串数据类型实际上是不可变的,尽管他似乎与自己矛盾。

他说:

In the new Delphi LLVM-based compiler,there is one string type,representing Unicode strings (UTF16),and mapped to the current string type in Delphi XE3 (an alias for the UnicodeString type on the Windows compiler). However,this new string type uses a different memory management model. The string type is still reference counted,but it is immutable,which means you cannot modify the string contents once it is constructed.

但他接着说:

In other words strings are now Unicode-based,soon-to-become immutable,and reference-counted.

并且:

Where things start to change,however,is when you modify an existing
string,not by replacing it with a new value (in which case you get a
brand new string) but when you modify one of its elements,as shown in
this line of code (and also in the prevIoUs section,where I
introduced the topic):

06000

All Delphi compilers use a copy-on-write semantics: If the string you
modify has more than one reference,it is first copied (adjusting the
reference counts of the varIoUs strings involved as required) and
later modified.

The new compiler does something very similar to the classic one. It
implements a copy-on-write mechanism,unless there is a single
reference to the string,in which case the string gets modified in
place. As an example,consider the following code,which outputs the
in-memory location of the actual string.

然后,他显示了一个具有突变字符串的iOS设备的图片

而在official documentation,我们有:

Strings are immutable (constant),so you cannot index into a string as
an array and manipulate the characters in a string. If you attempt to
modify a string,the Delphi mobile compilers might emit the message
W1068 Modifying strings in place may not be supported in the future
(Delphi). You can specify whether the message x1068 is emitted as a
warning or an error. In the Hints and Warnings page,set the warning
“Modifying strings in-place….” to “true” or “error”.

所以我解释所有这些意味着iOS编​​译器的XE4版本仍然有可变字符串。开发人员真的不希望您再次更改字符串,并告诉您,字符串在移动编译器上是不可变的。但他们似乎仍然是可变的。去搞清楚!

但是,您已被通知,在将来的版本中,字符串可能会变得不可变。

您现在可以通过设置为将来的版本做准备

{$WARN IMMUTABLE_STRINGS WARN}

这将让您了解变更的影响。如果你想扣上和停止变异的字符串,你可以这样做:

{$WARN IMMUTABLE_STRINGS ERROR}

一旦你这样做,你需要转换访问各个字符串元素的代码。我怀疑你会有多少这样的代码是惊讶的。我只编译了60万行代码,只看到了120个警告。其中大部分是在第三方单位。我已经看到了这个变化,但我真的不相信很多代码突变字符串。在绝大多数情况下,字符串是通过连接构建的,或者通过对格式等函数调用。该代码不受此影响。

我不认为有什么很大的陷阱。您可以使用{$ WARN IMMUTABLE_STRINGS …}让编译器引导您完成该过程。任何转换字符串的代码都应该转换为使用TStringBuilder。

至于不变性的好处,我把你转给Why .NET String is immutable?

如果您使用的是传统的Windows或OSX编译器,那么我看不到有任何令人信服的理由进行更改。 iOS编译器是全新的。对不可变字符串的更改已经浮动,但可能永远不会发生。它可能只发生在移动编译器上,从来没有传统的编译器。现在,我会坐得很紧,等待看看这一切如何发挥。

原文链接:https://www.f2er.com/delphi/103284.html

猜你在找的Delphi相关文章