Object reference counters in VFP
2009-08Aug-14
Visual FoxPro maintains a reference counter for every object. Whenever a reference to an object is stored in a variable or property, the reference counter is incremented by one. When the same property or variable is filled with a different value, or when it goes of scope, Visual FoxPro decrements the counter by one. Visual FoxPro releases the object once the counter reaches zero.
The syntax is very simple. If you want to increment the object reference counter, you call the IncrementRef() function passing the object as the only parameter. The following sample creates a form and stores the reference in a local variable. Normally, the form would be released as soon as the code finishes. That is, you would see the form flash very briefly. With the call to IncrementRef you basically create a dangling reference to the form letting the form stay around even after the code returns:
* Create a form with just a local referenceLocal loFormloForm = CreateObject("Form")loForm.Show()* Create artificial dangling referenceSet Library To ObjRef.FLLIncrementRef(loForm)Similarly you can force an object to release by decrementing the reference counter. Even so the method hasn't finished yet, the form is gone:
* Create a form Local loFormloForm = CreateObject("Form")loForm.Show()* Release formSet Library To ObjRef.FLLDecrementRef(m.loForm)Wait windowPlaying around with object reference counters isn't something you should normally do. Visual FoxPro doesn't expect this and in some cases might respond erratically. When you, for instance, execute the following code and then type in the Command Window, Visual FoxPro either crashes or brings up error messages.
Set Library To ObjRef.FLLDecrementRef(_Screen)