tags:

views:

77

answers:

3

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 call myObject := MyClass.Create; (constructor)?
+6  A: 

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.

Mason Wheeler
+2  A: 

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).

Rob Kennedy
A: 

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).

A. Bouchez
That's wrong. All *fields* of an object will be allocated when the instance is created. That is not necessarily true for a property because it could have Getter and Setter methods that do not require any memory to be allocated at instance creation time.
dummzeuch