Delphi object memory allocation
In Delphi, if I have a variable myObject : MyClass
, and MyClass
has a property that is a fixed-length array with 300 integers in it, when will the memory for it be allocated?
- When the scope of myObject is entered?
- When I cal开发者_运维百科l
myObject := MyClass.Create;
(constructor)?
Fixed-length arrays are allocated inline, so it exists as part of the instance size of MyClass and it gets allocated when you call the constructor.
If you really mean the object has a property, then no space at all is allocated for it. Properties are generalized interfaces to some other mode of access, either a field or a function.
If the property is backed by a field of the object, then, as Mason explained, the field exists as part of the object itself; the array's length directly affects the total size of the object (as given by the TObject.InstanceSize
method). The field has memory; the property doesn't.
If the property is backed by a function, then the function's return value generally gets allocated on the caller's stack and passed in as a "var" parameter. The function fills it and returns to the caller. Again, the property itself has no memory allocated for it.
You could have a hundred properties on an object that's only four bytes long (which is the minimum size for objects).
If, however, you actually meant a field, then it is allocated as part of the object during the call to TObject.NewInstance
. That method is called as part of the outer constructor's prologue ( as opposed to any calls to inherited constructors).
All properties content will be allocated when the instance is created.
Before the TClassName.Create call, there is only the pointer available in the stack or wherever it was declared: only 4 bytes.
When the Create method is called, the TObject.Newinstance method is executed:
class function TObject.NewInstance: TObject;
begin
Result := InitInstance(_GetMem(InstanceSize));
end;
The InstanceSize method will return the size (in bytes) containing all fixed-size (aka static) properties of the class.
Your 300 integers will be retrieved from the heap via this GetMem call. A few more memory is needed (inherited properties and some default values like the class type and the VMT).
精彩评论