// Indicate the source If You Need To reprint it
// Author: Xiaoyao Xiao
// Source: http://www.xy13.cn
It is estimated that many users who have used Delphi for many years do not know that Delphi supports stack objects.
Objects in C ++ can be created as heap objects or stack objects.
Common objects are inherited from tobject. This type of object needs to be created and released. Otherwise, a memory vulnerability occurs.
Stack objects do not need to be created or released. They are automatically cleared when the lifecycle is complete.
The following is a test of the effect.
Type
Pa = ^ ta;
Ta = Object
D1: integer;
D2: word;
D3: byte;
Constructor create;
Destructor destroy;
End;
Constructor ta. Create;
Begin
Showmessage ('create ');
End;
Destructor ta. Destroy;
Begin
Showmessage ('deststroy ');
End;
Procedure tform2.button1click (Sender: tobject );
VaR
A: Ta;
Begin
Showmessage (inttostr (A. D1); // you can directly access
Showmessage (inttostr (sizeof (TA); // 7
End;
The test shows that the constructor and destructor of the object are not called, and it looks very similar to packed record,
The heap object is a pointer and the size is always 4. The size of the stack object depends on the internal data. It is not a pointer variable.
Test the stack object and create it from the stack, that is, use the New Keyword, and add the constructor to the parameter during creation.
Procedure tform2.button1click (Sender: tobject );
VaR
A: Pa;
Begin
New (A, create );
Showmessage (inttostr (a ^. D1 ));
Dispose (A, destroy );
End;
If new is followed by a parameter. The constructor will not be executed, and the object will be initialized.
Here is the difference between only packed record. Record cannot contain constructor; otherwise, compilation fails.
I don't think it makes much sense. I'm happy with it. If the D7 user is still helpful, because the record does not support the method.
-------------------------------------------------------------------------
It's a pity that I only know it after years of ignorance.
One of my custom databases has a data header structure. If it is defined as an object, the database is upgraded.
The version is much more convenient.
Always use D7.
It is said that there will be record objects after d2007.