delphi 变量是否默认初始化为一个值? [英] Are delphi variables initialized with a value by default?

查看:19
本文介绍了delphi 变量是否默认初始化为一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Delp and I've been running some tests to see what object variables and stack variables are initialized to by default:

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

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

This is the behaviour I'm used to from other languages, but I'm wondering if it's safe to rely on it in Delphi? For example, I'm wondering if it might depend on a compiler setting, or perhaps work differently on different machines. Is it normal to rely on default initialized values for objects, or do you explicitly set all instance variables in the constructor?

对于堆栈(过程级)变量,我的测试表明未初始化的布尔值是真的,未初始化的整数是 2129993264,未初始化的对象只是无效的指针(即不是 nil).我猜规范是在访问它们之前总是设置过程级变量?

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?

推荐答案

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

Yes, this is the documented behaviour:

  • 对象字段始终初始化为 0、0.0、''、False、nil 或任何适用的值.

  • Object fields are always initialized to 0, 0.0, '', False, nil or whatever applies.

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

Global variables are always initialized to 0 etc as well;

Local reference-counted* 变量总是初始化为 nil 或 '';

Local reference-counted* variables are always initialized to nil or '';

本地非引用计数*变量未初始化,因此您必须先分配一个值才能使用它们.

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

我记得 Barry Kelly 在某处为引用计数"写了一个定义,但找不到任何更多,所以同时应该这样做:

I remember that Barry Kelly somewhere wrote a definition for "reference-counted", but cannot find it any more, so this should do in the meantime:

reference-counted == 本身是引用计数的,或者直接或间接包含字段(用于记录)或元素(用于引用计数的数组),例如:string、variant、interface动态数组静态数组 包含这些类型.

reference-counted == that are reference-counted themselves, or directly or indirectly contain fields (for records) or elements (for arrays) that are reference-counted like: string, variant, interface or dynamic array or static array containing such types.

注意事项:

  • record 本身不足以成为引用计数
  • 我还没有用泛型尝试过这个
  • record itself is not enough to become reference-counted
  • I have not tried this with generics yet

这篇关于delphi 变量是否默认初始化为一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆