默认情况下是否使用值初始化delphi变量

默认情况下是否使用值初始化delphi变量

本文介绍了默认情况下是否使用值初始化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,而非正则化的对象​​只是无效的指针(即不是零)。我猜这个规范是在访问它们之前总是设置过程级变量?

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;

本地引用计数*变量为始终初始化为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.

我记得在某处写了一个引用计数的定义,但是找不到它,所以在此期间应该这样做:

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:

注意:


  • record 本身不足以成为引用计数

  • 我还没有尝试过这个泛型,但是

  • record itself is not enough to become reference-counted
  • I have not tried this with generics yet

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

1403页,肝出来的..

09-06 09:56