The delphi Object Model (Part II)
Sample Chapter of Delphi in A NutshellProduct:
Delphi All Versions
Category: Oo-RelatedSkill Level: Scoring: Last Update: 05/21 / 2000Search Keys: Delphi Delphi3000 Article Object Model OOP InterfaceStimeS Scored: 7Visits:
5557
Uploader: Stefan Walthercompany: Bluestep.com It-ConsultingReference: ray Lischner - O'Reilly Question / Problem / Abstract:
Delphi's support for object-oriented programming is rich and powerful. In addition to traditional classes and objects, Delphi also has interfaces (similar to those found in COM and Java), exception handling, and multithreaded programming. This chapter covers Delphi's object model in depth YOULD Already Be Familiar With Standard Pascal and general Principles of Object-Oriented Programming.
Answer: Reprinted with permission from O'Reilly & Associates Object Life Cycle For most objects, you call a constructor to create the object, use the object, and then call Free to free the object Delphi handles all the other details for you Sometimes.. ., though, you need to know a little more about the inner mechanisms of Delphi's object model Example 2-8 shows the methods that Delphi calls or simulates when it creates and frees an object Example 2-8:. The Life Cycle of an Object Type
Tsomething = Class
Procedure dosomething;
END;
VAR
REF: Tsomething;
Begin
Ref: = tsomething.create;
Ref.dosomething;
REF.FREE;
End; // The Hidden Code in The Constructor Looks Something Like this:
Function Tsomething.create (IsclassRef: Boolean): Tsomething;
Begin
IF IsclassRef Then
Try
// allocate the New Object.
Self: = tsomething.newinstance;
// newinstance initializes the object in The Same That That
// InitInstance Does. If you override newinstance, thing, // and do not call the inherited newinstance, you must call
// InitInstance. The Call is shown Below, so you know What
// happens, but repeem That Ordinarily Delphi Does Not
// Actually Call InitInstance.
InitInstance (Self);
// do the real work of the constructor, but without all the
// Class Reference Overhead. Delphi Does Not Really Call THE
// Constructor recursively.
Self.create (FALSE);
Self.AFTERCONSTRUCTION;
Except
// if any Exception Occurs, Delphi Automatic or Calls the
// Object's Destructor.
Self.destroy;
end
Else
Self.create (FALSE);
Result: = Self;
END;
// The Hidden Code in The Destructor Looks Something Like this:
Procedure tsomething.destroy (deallocate: boolean);
Begin
IF deallocate thein
Self.beforeDestruction;
// Delphi Doesn't Really Call The Destructor Recursively, But
// this is Where The Destructor's Real Work Takes Place.
Self.destroy (false);
IF deallocate thein
Begin
// Delphi Doesn't really call cleanupinstance. Instead, the
// FreeInstance Method Does the cleanup. If you override
// FreeInstance and do not call the inherited freeInstance,
// You Must Call Cleanupinstance to Clean Up Strings,
// Dynamic Arrays, And Variant-Type Fields.
Self.cleanupinstance;
// Call FreeInstance to Free The Object's Memory.
Self.FreeInstance;
END;
end; Access Levels Like C and Java, Delphi has different access levels that determine which objects can access the fields, methods, and properties of another object The access levels are as follows:. private Declarations that are declared private can be accessed only by the class's own methods or by any method, procedure, or function defined in the same unit's implementation section Delphi does not have C -.. style friend declarations or Java-style package level access The equivalent in Delphi is to declare package or friend classes in the same unit, which gives them access to the private and protected parts of every class defined in the same unit. protected A protected declaration can be accessed from any method of the class or its descendants. The descendent classes can reside in different units. public public Methods Have Unrestricted Access. Any Method, Function, or Procedure CAN Access A Public Declaration. Unless Directive (See Chapter Directive (See Chapter 8, Compiler Dire ctives, for details), the default access level is public published Published declarations are similar to public declarations, except that Delphi stores runtime type information for published declarations Some declarations can not be published;... see Chapter 3 for details If a class or a base class uses the $ M directive, the default access level is published TIP:.. Delphi's IDE declares fields and methods in the initial unnamed section of a form declaration inherits from TPersistent Because TForm, which uses the $ M
directive, the initial section is published. In other words, the IDE declares its fields and methods as published. When Delphi loads a form description (.dfm file), it relies on the published information to build the form object. The IDE relies on the initial, unnamed section of the form class. If you modify that section, you run the risk of disabling the IDE's form editor. automated Automated declarations are similar to public declarations, except that Delphi stores additional runtime type information to support OLE automation servers. Automated declarations are obsolete; you should use Delphi's type library editor instead, but for now, they remain a part of the language for backward compatibility A future release of Delphi might eliminate them entirely Chapter 3 describes automated declarations in more depth A derived... Class Can Increase The Access Level of a property by Redeclaring The Property Under The New Access Level (EG, CHANGE PROTECTED TO PUBLIC). You canNot Decrease A property's access level, and you can not change the visibility of a field or method. You can override a virtual method and declare the overridden method at the same or higher access level, but you can not decrease the access level. Hiding a Constructor Sometimes, a class is not for public use, but is a helper class whose use is entirely subservient to another class In that case, you probably want to make the constructors for the helper class private or protected, but this is tricky TObject declares a public constructor..: Create. Even though the helper class'
s constructors are private or protected, you can call the public Create constructor inherited from TObject. Although you can not change the access level of the inherited Create constructor, you can hide it with another public constructor. Because the derived constructor should not be called, it CAN rasse: type: type: type: type;
TPRIVATEHELPER = Class
Private
// Tpublic is the only class allowed to
// Call The Real Construction:
Constructor Create (Owner: Tpublic);
OVERLOAD;
public
// hide Tobject.create, in case someone
// Accidentally Tries to create a
// TPRIVATEHELPER INSTANCE.
Constructor crete;
REINTROAD; OVERLOAD;
END;
TPUBLIC = Class
Private
Fhelper: tprivatehelper;
public
Constructor crete;
DESTRUCTOR DESTROY;
END;
Constructor tprivateHelper.create;
Begin
Raise Exception.create ('Programming Error')
END;
Constructor TPUBLIC.CREATE;
Begin
// this is the only place where Where WHERE
// TPRIVATEHELPER IS CREATED.
Fhelper: = tprivatehelper.create (Self);
end;.. Properties A property looks like a field but can act like a method Properties take the place of accessor and mutator methods (sometimes called getters and setters), but have much more flexibility and power Properties are vital to Delphi's IDE, and you can also use properties in many other situations. A property has a reader and writer to get and set the property's value. The reader can be the name of a field, a selector for an aggregate field, or a method that returns the property value. The writer can be a field name, a selector for an aggregate field, or a method that sets the property value. You can omit the writer to make a read-only property. You can also omit the reader to create a write-only property , but the uses for such a beast are limited. Omitting both the reader and the writer is pointless, so Delphi does not let you do so. Most readers and writers are field names or method names, but you can also refer to part of an Aggregate Field (Record or Array). if A Reader or writer refers to an array element, the array index must be a constant, and the field's type can not be a dynamic array. Records and arrays can be nested, and you can even use variant records. Example 2-9 shows an extended rectangle type , Similar to the Windows Treat Type, But Because IT IS A Class, IT Has Properties And Methods.example 2-9: Properties Readers and Writers TRECTEX = Class (TPERSIStent) private
R: TRECT;
Function GetHeight: Integer;
Function getWidth: integer;
Procedure setHeight (Const value: integer);
Procedure setWidth; Const Value: Integer;
public
Constructor Create (Const R: TRECT); OVERLOAD;
Constructor Create (Left, Top, Right, Bottom: Integer; Overload;
Constructor Create (Const Topleft, Bottomright: Tpoint); OverLoad; Procedure Assign (Source: TPERSIStent); OVERRIDE;
Procedure Inflate (x, y: integer);
Procedure INTERSECT (Const R: TRECTEX);
Function isempty: boolean;
Function ISEQUAL (Const R: TRECTEX): Boolean;
Procedure Offset (X, Y: Integer);
Procedure Union (Const R: TRECTEX);
Property Topleft: TPoint Read R.Topleft Write R.Topleft;
Property Bottomright: Tpoint Read R.BOTTOMRIGHT WRITE R.BOTTOMRIGHT;
Property RECT: TRECT READ R WRITE R;
Property Height: Integer Read GetHeight Write SetHeight;
Property Width: Integer Read GetWidth Write SetWidth
Published
Property Left: Integer Read R.Left Write R.Left Default 0;
Property Right: Integer Read R.right Write R.right Default 0;
Property top: Integer Read R.Top Write R.Top Default 0;
Property Bottom: Integer Read R.Bottom Write R.Bottom Default 0;
end;.. Array properties Properties come in scalar and array flavors An array property can not be published, but they have many other uses The array index can be any type, and you can have multidimensional arrays, too For array-type properties, you. must use read and write methods -.. you can not map an array-type property directly to an array-type field you can designate one array property as the default property you can refer to the default property by using an object reference and an array Subscript withouting The Property Name, AS Shown in Example 2-10. EXAMPLE 2-10: USING A Default Array Property Type
Texample = Class
...
Property Items [i: integer]: Integer Read GetItem Write SetItem
Property Chars [C: Char]: Char Read GetChar Write setcha; DEFAULT
END;
VAR
Example: texample;
I: integer;
C: char;
Begin
EXAMPLE: = texample.create;
I: = example.Items [4]; // must mention protection name explicitlyc: = example ['x']; // array proteTy is default
C: = Example.Chars [ 'X']; // Same as previous line Indexed properties You can map many properties to a single read or write method by specifying an index number for each property The index value is passed to the read and. write methods to differentiate one property from another. You can even mix array indices and an index specifier. The reader and writer methods take the array indices as the first arguments, followed by the index specifier. default values A property can also have stored and default directives. This information has no semantic meaning to the Delphi Pascal language, but Delphi's IDE uses this information when storing form descriptions. The value for the stored directive is a Boolean constant, a field of Boolean type, or a method that takes no arguments and returns a Boolean result. The value for the default directive is a constant value of the same type as the property. Only enumerated, integer, and set-type properties can have a default value. The stored and default directives have meaning only for published properties. To distinguish a default array from a default value, the default array directive comes after the semicolon that ends the property declaration. The default value directive appears as part of the property declaration. See the default directive in Chapter 5 for details. Using propertiesA common approach to writing Delphi classes is to make all fields private, and declare public properties to access the fields. Delphi imposes no performance penalty for properties that access fields directly. By using properties you get the added benefit of being Able to change the importation at a future date, say to add validation when a field '
s value changes. You can also use properties to enforce restricted access, such as using a read-only property to access a field whose value should not be changed. Example 2-11 shows some of the different ways to declare and use properties. Example 2-11: Declaring and use printerties TypetCustomer = Record
Name: String;
TaxidNumber: String [9];
END;
Taccount = Class
Private
FCustomer: TCUSTOMER;
FBALANCE: CURRENCY;
Fnumber: cardinal;
Procedure setBalance (NewBalance: Currency);
Published
Property Balance: Currency Read Fbalance Write setBalance;
Property Number: Cardinal Read Fnumber; // Cannot Change Account #
Property Custname: String Read Fcustomer.Name;
END;
Tsavingsaccount = Class (Taccount)
Private
FINTERESTRATE: INTEGER;
Published
Property InterestRate: Integer Read FinterestRate
Write FinterestRate Default DefaultInterestRate;
END;
TLINKEDACCOUNT = Class (TOBJECT)
Private
Faccounts: array [0..1] of taccount;
Function getAccount (INDEX: Integer): Taccount;
public
// Two Ways for Properties To Access An Array: Using An Index
// or referring to an array element.
Property CHECKING: Taccount Index 0 Read getaccount;
Property Savings: Taccount Read Faccounts [1];
END;
TaccountList = Class
Private
FList: TLIST;
Function getAccount (INDEX: Integer): Taccount;
Procedure setAccount (INDEX: Integer; Account: taccount);
Function getCount: Integer;
protected
Property List: Tlist Read flist;
public
Property Count: Integer Read GetCount;
Property Accounts [INDEX: Integer]: Taccount Read getaccount
Write setAccount; default;
END;
Procedure Taccount.setBalance: Currency;
Begin
IF newbalance <0 THEN
Raise eoverdrawnexception.create;
"= newbalance;
Function TLINKEDACCOUNT.GETACCOUNT (INDEX: Integer): Taccount;
Begin
Result: = Faccounts [Index]
END;
Function TaccountList.getCount: Integer;
Begin
Result: = List.count
END;
Function TaccountList.getaccount (INDEX: Integer): Taccount;
Begin
Result: = List [index]
END;
Procedure TaccountList.setAccount (INDEX: Integer; Account: Taccount);
Begin
FLIST [INDEX]: = Account
end; Class-type properties Properties of class type need a little extra attention The best way to work with class-type properties is to make sure the owner object manages the property object In other words, do not save a reference to other.. objects, but keep a private copy of the property object. Use a write method to store an object by copying it. Delphi's IDE requires this behavior of published properties, and it makes sense for unpublished properties, too. The only exception to the rule for class-type properties is when a property stores a reference to a component on a form. in that case, the property must store an object reference and not a copy of the component. Delphi's IDE stores component references in a .dfm file by storing only the component name. When the .dfm is loaded, Delphi looks up the component name to restore the object reference. If you must store an entire component within another component, you must delegate all properties of the inner component. Make sure the p roperty's class inherits from TPersistent and that the class overrides the Assign method Implement your property's write method to call Assign (TPersistent -.. in the Classes unit - is not required, but it '
s the easiest way to copy an object. Otherwise, you need to duplicate the Assign method in whatever class you use.) The read method can provide direct access to the field. If the property object has an OnChange event, you might need to set that so your object is notified of any changes. Example 2-12 shows a typical pattern for using a class-type property. The example defines a graphical control that repeatedly displays a bitmap throughout its extent, tiling the bitmap as necessary. The Bitmap property . stores a TBitmap object Example 2-12: Declaring and Using a class-type Property unit Tile; interface uses SysUtils, Classes, Controls, Graphics; type // Tile a bitmap TTile = class (TGraphicControl) private fBitmap: TBitmap; procedure SetBitmap (NewBitmap: TBitmap); procedure BitmapChanged (Sender: TObject); protected procedure Paint; override; public constructor Create (Owner: TComponent); override; destructor Destroy; override; published property Align; property Bitmap: TBitmap read fBitma p write SetBitmap; property OnClick; property OnDblClick; // Many other properties are useful, but were omitted to save space // See TControl for a full list end;.. implementation {TTile} // Create the bitmap when creating the control. constructor TTile.Create (Owner: TComponent); begin inherited; fBitmap: = TBitmap.Create; fBitmap.OnChange:. = BitmapChanged; end; // Free the bitmap when destroying the control destructor TTile.Destroy; begin FreeAndNil (fBitmap); inherited; end; // When the bitmap changes, redraw the control procedure TTile.BitmapChanged.. (Sender: TObject); begin Invalidate; end; // Paint the control by tiling the bitmap If there is no // bitmap, don ' TPAINT Anything. Procedure TTILE.PAINT; VAR X, Y: Integer;
Begin if (Bitmap.width = 0) The EXIT; Y: = 0; While Y s methods, or it can delegate the implementation to a property, whose value is an interface. The simplest way to implement the _AddRef, _Release, and QueryInterface methods is to inherit them from TInterfacedObject or one of its derived classes, but you are free to inherit from any other class if you wish to define the methods yourself. A class implements each of an interface's methods by declaring a method with the same name, arguments, and calling convention. Delphi automatically matches the class's methods with the interface's methods. If you want to use a different method name, you can redirect an interface method to a method with a different name. The redirected method must have the same arguments and calling convention as the interface method. This feature is especially important when a class implements multiple interfaces with Identical Method Names. See The Class Keyword In Chapter 5 for More Information About Redirecting Methods. a class of an i nterface to a property that uses the implements directive. The property's value must be the interface that the class wants to implement. When the object is cast to that interface type, Delphi automatically fetches the property's value and returns that interface. See the implements directive in Chapter 5 for details. for each non-delegated interface, the compiler creates a hidden field to store a pointer to the interface's VMT. The interface field or fields follow immediately after the object's hidden VMT field. Just as an object reference is really a pointer To The Object's Hidden Vmt Field, An Interface Reference Is A Pointer To The Interface ' s hidden VMT field. Delphi automatically initializes the hidden fields when the object is constructed. See Chapter 3 to learn how the compiler uses RTTI to keep track of the VMT and the hidden field. Reference counting The compiler generates calls to _AddRef and _Release to manage the lifetime of interfaced objects. to use Delphi's automatic reference counting, declare a variable with an interface type. When you assign an interface reference to an interface variable, Delphi automatically calls _AddRef. When the variable goes out of scope, Delphi automatically calls _Release. The behavior of _AddRef and _Release is entirely up to you. If you inherit from TInterfacedObject, these methods implement reference counting. The _AddRef method increments the reference count, and _Release decrements it. When the reference count goes to zero, _Release frees the object. IF you inherit from a Different Class, You Can DEFINE THESE Methods to do anything You Want. You Should IMPLEMENT Queryinterface C orrectly, though, because Delphi relies on it to implement the as operator. Typecasting Delphi calls QueryInterface as part of its implementation of the as operator for interfaces. You can use the as operator to cast an interface to any other interface type. Delphi calls QueryInterface to obtain the new interface reference. If QueryInterface returns an error, the as operator raises a runtime error. (The SysUtils unit maps the runtime error to an EIntfCastError exception.) you can implement QueryInterface any way you want, but you probably want to use The Same Approach Taken By TinterFaceDObject. EXAMPLE 2-13 Shows A Class That IMPLEments Queryinterface Normal, But Usees Stubs for _addref and _release. Later in this section, you Ll see how useful this class can be. EXAMPLE 2-13: Interface Base Class Without Reference Counting TypetnorefCount = Class (Tobject, IUnknown) protected Function QueryInterface (Const IID: Tguid; Out Obj): hResult; stdcall; Function _addref: integer; stdcall; Function _Release: integer; stdcall; END; Function Tnorefcount.QueryInterface (Const IID: Tguid; Out Obj): hResult; Begin IF GetInterface (IID, OBJ) THEN Result: = 0 Else Result: = windows.e_nointerface; END; Function TNOREFCOUNT._ADDREF: Integer; Begin Result: = -1 END; Function TNOREFCOUNT._RELEASE: Integer; Begin Result: = -1 end;. Interfaces and object-oriented programming The most important use of interfaces is to separate type inheritance from class inheritance Class inheritance is an effective tool for code reuse A derived class easily inherits the fields, methods, and properties of a base class,. and thereby avoids reimplementing common methods. In a strongly typed language, such as Delphi, the compiler treats a class as a type, and therefore class inheritance becomes synonymous with type inheritance. In the best of all possible worlds, though, types and classes are entirely separate. Textbooks on object-oriented programming often describe an inheritance relationship as an "is-a" relationship, for example, a TSavingsAccount "is-a" TAccount. you can see the same idea in Delphi's is operator, where you test whether An Account Variable Is Tsavingsaccount. Outside of Textbook Examples, Though, Simple Is-a Relationships Break Down. A Square Is A Rectangle, But That Doesn't Mean You Want To Derive Tsquare Fr om TRectangle. A rectangle is a polygon, but you probably do not want to derive TRectangle from TPolygon. Class inheritance forces a derived class to store all the fields that are declared in the base class, but in this case, the derived class doesn ' t need that information. A TSquare object can get away with storing a single length for all of its sides. A TRectangle object, however, must store two lengths. A TPolygon object needs to store many sides and vertices. The solution is to separate the type inheritance (a square is a rectangle is a polygon) from class inheritance (class C inherits the fields and methods of class B, which inherits the fields and methods of class A). Use interfaces for type inheritance, so you can leave class inheritance To do what it does best: inheriting fields and methods, isquare inherits from Irectangle, Which inherits from iPolygon. The interfaces Follow the "IS-A" relationship Entirely separate from the interfaces, the class TSquare implements ISquare, IRectangle, and IPolygon TRectangle implements IRectangle and IPolygon TIP:... The convention in COM programming is to name interfaces with an initial I. Delphi follows this convention for all interfaces Note. that it is a useful convention, but not a language requirement. On the implementation side, you can declare additional classes to implement code reuse. for example, TBaseShape implements the common methods and fields for all shapes. TRectangle inherits from TBaseShape and implements the methods in a way that make sense for rectangles. TPolygon also inherits from TBaseShape and implements the methods in a way that make sense for other kinds of polygons. A drawing program can use the shapes by manipulating IPolygon interfaces. Example 2-14 shows simplified classes and Interfaces for this Scheme. NOTICE How Each Interface Has A Guid (Global Unique Identifier) in ITS Declaration. The Guid IS necessary for using QueryInterface If you need the GUID of an interface (in an explicit call to QueryInterface, for example), you can use the interface name Delphi automatically converts an interface name to its GUID Example 2-14:... Separating Type and Class hierarchies typeishape = interface ['{50f6d851-f4eb-11d2-88ac-00104bcac44b}'] Procedure Draw (Canvas: Tcanvas); Function getPosition: tpoint; Procedure setPosition (Value: tpoint); Property Position: Tpoint Read getPosition Write setPosition; END; Ipolygon = interface (ishape) ['{50F6D852-F4EB-11D2-88AC-00104BCAC44B}'] Function Numvertices: integer; Function Numsides: Integer; Function SideLength: Integer; Function Vertex (INDEX: Integer): TPOINT; END; IRECTANGLE = Interface (IPOLYGON) ['{50F6D853-F4EB-11D2-88AC-00104BCAC44B}'] END; Isquare = interface (IRECTANGLE) [{50f6d854-f4eb-11d2-88ac-00104bcac44b} '] Function Side: Integer; END; TBASESHAPE = Class (TNOREFCOUNT, ISHAPE) Private FPSITION: TPOINT; Function getPosition: tpoint; Procedure setPosition (Value: tpoint); public Constructor create; Procedure Draw (canvas: tcanvas); virtual; abstract; Property Position: Tpoint Read fposition Write setPosition; END; TPOLYGON = Class (TBASESHAPE, IPOLYGON) Private Fvertices: array of tpoint; public Procedure Draw (Canvas: Tcanvas); OVERRIDE; Function Numvertices: integer; Function Numsides: Integer; Function SideLength: Integer; Function Vertex (INDEX: Integer): TPOINT; END; TRECTANGLE = Class (TBASESHAPE, IPOLYGON, IRECTANGLE) Private FRECT: TRECT; public Procedure Draw (Canvas: Tcanvas); OVERRIDE; Function Numvertices: integer; Function Numsides: Integer; Function SideLength: Integer; Function Vertex (INDEX: Integer): TPOINT; END; Tsquare = Class (TBASESHAPE, IPOLYGON, IRECTANGLE, ISQUARE) Private Fside: integer; public Procedure Draw (Canvas: Tcanvas); OVERRIDE; Function Side: Integer; Function Numvertices: integer; Function Numsides: Integer; Function SideLength: Integer; Function Vertex (INDEX: Integer): TPOINT; end;. A derived class inherits the interfaces implemented by the ancestors' classes Thus, TRectangle inherits from TBaseShape, and TBaseShape implements IShape so TRectangle implements IShape Inheritance of interfaces works a little differently Interface inheritance is merely a typing convenience, so you don.. 't have to retype a lot of method declarations. When a class implements an interface, that does not automatically mean the class implements the ancestor interfaces. A class implements only those interfaces that are listed in its class declaration (and in the declaration for ancestor classes). Thus, even though IRectangle inherits from IPolygon, the TRectangle class must list IRectangle and IPolygon explicitly. to implement a type hierarchy, you might not want to use reference counting. Instead, you will rely on explicit memory management, the way you Do for Normal Delphi Objects. in this case, IT ' s best to implement the _AddRef and _Release methods as stubs, such as those in the TNoRefCount class in Example 2-13. Just be careful not to have any variables that hold stale references. A variable that refers to an object that has been freed can cause problems if you use the variable. An interface variable that refers to an object that has been freed will certainly cause problems, because Delphi will automatically call its _Release method. In other words, you never want to have variables that contain invalid pointers, and working with interfaces that do not use reference counting forces you to behave. COM and Corba Delphi interfaces are also useful for implementing and using COM and Corba objects. you can define a COM server that implements many interfaces, and Delphi automatically manages the COM aggregation for You. The Runtime Library Contains Many Classes That Make It Easier To Define COM Servers, Class Factories, And So on. Because these Classes Are Not Part of The Delphi Pasc al language, they are not covered in this book. Consult the product documentation to learn more. Reference Counting The previous section discusses how Delphi uses reference counting to manage the lifetime of interfaces. Strings and dynamic arrays also use reference counting to manage their lifetimes. The compiler generates appropriate code to keep track of when interface references, strings, and dynamic arrays are created and when the variables go out of scope and the objects, strings, and arrays must be destroyed. Usually, the compiler can handle the reference counting automatically And Everything Works the Way the you expect it to. Sometimes, Though, You NEED to Give a hint to the compiler. For example, if you declare a record that contains a reference counted field, and you use GetMem to allocate a new instance of the record, you must call Initialize, passing the record as an argument. Before calling FreeMem, you must call Finalize. Sometimes , you want to keep a reference to a string or interface after the variable goes out of scope, that is, at the end of the block where the variable is declared. For example, maybe you want to associate an interface with each item in a TListView. You can do this by explicitly managing the reference count. When storing the interface, be sure to cast it to IUnknown, call _AddRef, and cast the IUnknown reference to a raw pointer. When extracting the data, type cast the pointer to IUnknown . you can then use the as operator to cast the interface to any desired type, or just let Delphi release the interface. for convenience, declare a couple of subroutines to do the dirty work for you, and you can reuse these subroutines any time you NEED TO . Retain an interface reference Example 2-15 shows an example of how you can store an interface reference as the data associated with a list view item Example 2-15:. Storing Interfaces in a List View // Cast an interface to a Pointer such That the reference // count is increment and the interface will not be freed // Until You Call ReleaseIunknown. Function RefiunkNown (Const Intf: iunknown): Pointer; Begin INTF._ADDREF; // Increment The Reference Count. Result: = Pointer (INTF); // Save The Interface Pointer. END; // Release the interface whose value is stored in The Pointer P. Procedure ReleaseiunkNown (P: Pointer); VAR INTF: IUNKNOWN; Begin Pointer (intf): = P; // delphi releases the interface when intf goes out of scope.end; // when the user copy to the button, add. Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT); VAR Item: TLISTITEM; Begin Item: = listview1.items.add; Item.caption: = 'stuff'; Item.Data: = REFIUNKNOWN (GetInTf as iUnknown); END; // when the list view is destroyed or the list item is destroyed // for Any Other Reason, Release the interface, TOO. Procedure TFORM1.ListView1deletion (Sender: Tobject; Item: TLISTIM); Begin ReleaseiunkNown (Item.Data); END; //En the user selects the list view item, do something with the // associated interface. Procedure TFORM1.ListView1click (Sender: TOBJECT); VAR INTF: IMYINTERFACE; Begin INTF: = IUNKNOWN (ListView1.Selected.data) as ImyInterface; INTF.DOSMETHINGUSEFUL; end; You can also store strings as data Instead of using _AddRef, cast the string to a Pointer to store the reference to the string, then force the variable to forget about the string When the variable goes out of scope, Delphi will not.. free the string, because the variable has forgotten all about it. After retrieving the pointer, assign it to a string variable that is cast to a pointer. When the subroutine returns, Delphi automatically frees the string's memory. Be sure your program does not retain any pointers to memory that is about to be freed Again, convenience subroutines simplify the task Example 2-16 shows one way to store strings Example 2-16:... Storing Strings in a List View // Save a reference to a string and Return A Raw Pointer // To the string. Function Refstring (const s: string): Pointer; VAR Local: String; Begin Local: = s; // increment the reference count.result: = Pointer (local); // Save the string pointer. Pointer: = nil; // prevent Decrementing The Ref Count. END; // Release A String That Was Reference with refstring. Procedure ReleaseString (P: Pointer); VAR Local: String; Begin Pointer (local): = P; // Delphi Frees the string when local goes out of scope. END; //Hen the user copys the button, add an item to the list view // and save an additional, Hidden String. Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT); VAR Item: TLISTITEM; Begin Item: = listview1.items.add; Item.caption: = edit1.text; Item.Data: = refstring (edit2.text); END; // Release the string when the list view item is destroyed // for Any Reason. Procedure TFORM1.ListView1deletion (Sender: Tobject; Item: TLISTIM); Begin ReleaseString (item.data); END; // Retrieve The String When The User Selects The List View Item. Procedure TFORM1.ListView1click (Sender: TOBJECT); VAR Str: string; Begin If listview1.selected <> nil kil Begin Str: = string (listview1.selected.data); ShowMessage (STR); END; END; script>