[fpc-devel] Const optimization is a serious bug

Martin fpc at mfriebe.de
Tue Jul 5 20:12:46 CEST 2011


On 05/07/2011 18:56, Alexander Klenin wrote:
> On Wed, Jul 6, 2011 at 03:44, Jonas Maebe<jonas.maebe at elis.ugent.be>  wrote:
>> 2) All such incorrect usage should be removed from LCL and FCL
>> (for example: event handlers in LCL and TStrings methods in FCL).
> Well, then the situation is hopeless ;-)

TStringList could be made save, and keep the const. Just add additonal 
references where needed.

At least with respect to the callback evets (OnChanging, OnChange...)
inherited classes have to take care for them self.

e.g look at

Function TStringList.Add(const S: string): Integer;
  no events, calls  =>  InsertItem (Result,S);

Procedure TStringList.InsertItem(Index: Integer; const S: string);
   => event: Changing
   insert the new value
   => event: Change

in the 2 event the string could be lost/ For the 2nd event that is no 
problem (because it has already been added, and got it's reference via 
the list)

but if it was lost in the first, then corrupted data was added.
Yet all that is needed is keep a local copy of the sting to be added, 
before calling the event

Since the const is kept, "Add " still saves exception frame. InsertItem 
would need an exception frame ( it may be possible to avoid it, but with 
a lot of trickery only. not sure)


> Note that the only reason TString/TStringList does not break too often is that
> the only way to get access to an element is by calling Get, which
> increments refcount
Not getting this part?

The local variable in Add/InsertItem may not have a ref count. but once 
Added, the entry in the list does of ourse have a ref count...

This does increase the refcount
   Flist^[Index].FString:=S;




More information about the fpc-devel mailing list