Are delphi variables initialized with a value by default?

我是 Delphi 的新手,我一直在运行一些测试,看看默认情况下对象变量和堆栈变量的初始化是什么:

TInstanceVariables = class
fBoolean: boolean; // always starts off as false
fInteger: integer; // always starts off as zero
fObject: TObject; // always starts off as nil
end;

这是我在其他语言中习惯的行为,但我想知道在特尔斐依赖它是否安全?例如,我想知道它是否依赖于编译器设置,或者在不同的机器上工作方式不同。依赖于对象的默认初始化值是正常的吗,还是在构造函数中显式设置所有实例变量?

As for stack (procedure-level) variables, my tests are showing that unitialized booleans are true, unitialized integers are 2129993264, and uninialized objects are just invalid pointers (i.e. not nil). I'm guessing the norm is to always set procedure-level variables before accessing them?

69993 次浏览

类字段默认为零。这是有文档说明的,所以您可以依赖它。 除非字符串或接口被设置为零,否则本地堆栈变量是未定义的。

是的,这是记录在案的行为:

  • 对象字段总是初始化为0.0.0、”、 False、 nil 或其他应用。

  • 全局变量也总是初始化为0等;

  • 局部引用计数 * 变量始终初始化为“零”或“ ;

  • Local non reference-counted* variables are uninitialized so you have to assign a value before you can use them.

我记得 Barry Kelly在某个地方写了一个“参考计数”的定义,但是再也找不到了,所以同时应该这样做:

引用计数 = = 本身是引用计数的,或 直接或间接包含字段(用于记录)或元素(用于 arrays) that are reference-counted like: string, variant, interface or dynamic array or 静态数组静态数组 containing such types.

备注:

  • record本身不足以成为参考计数
  • 我还没有在泛型中尝试过这种方法

全局变量和对象实例数据(字段)始终初始化为零。 Local variables in procedures and methods are not initialized in Win32 Delphi; their content is undefined until you assign them a value in code.

即使一种语言确实提供了默认的初始化,我也不认为您应该依赖它们。对值进行初始化可以使那些可能不知道语言中默认初始化的其他开发人员更加清楚,并防止编译器之间出现问题。

以下是来自 Ray Lischners Delphi in a Nutshell 第二章的一段话

"When Delphi first creates an object, all of the fields start out empty, that is, pointers are initialized to nil, strings and dynamic arrays are empty, numbers have the value zero, Boolean fields are False, and Variants are set to Unassigned. (See NewInstance and InitInstance in Chapter 5 for details.)"

确实,局部范围内的变量需要被初始化... ... 我认为上面关于“全局变量被初始化”的评论是可疑的,直到提供了一个参考——我不相信这一点。

编辑。 Barry Kelly 说你可以相信它们是零初始化的,因为他是 Delphi 编译器团队的成员,所以我相信这是成立的:)谢谢 Barry。

来自 Delphi 2007帮助文件:

Ms-help://borland.bds5/devcommon/variable _ xml. html

“如果没有显式初始化全局变量,编译器会将其初始化为0。”

我对你给的答案有点不满。Delphi 将全局变量和新创建的对象的内存空间归零。虽然这个 NORMALLY意味着它们已经初始化,但有一种情况并非如此: 具有特定值的枚举类型。如果零不是合法值呢?

Global variables that don't have an explicit initializer are allocated in the BSS section in the executable. They don't actually take up any space in the EXE; the BSS section is a special section that the OS allocates and clears to zero. On other operating systems, there are similar mechanisms.

You can depend on global variables being zero-initialized.

正如一个边注(因为您是 Delphi 的新手) : 全局变量可以在声明它们时直接初始化:

var myGlobal:integer=99;

Newly introduced (since Delphi 10.3) inline variables are making the control of initial values easier.

procedure TestInlineVariable;
begin
var index: Integer := 345;
ShowMessage(index.ToString);
end;