[fpc-pascal] a queried interface destroyed after writeln the address of it
Jonas Maebe
jonas.maebe at elis.ugent.be
Thu Aug 23 10:06:28 CEST 2012
ZAN DoYe wrote on Thu, 23 Aug 2012:
> I don't know if it's an undefined behavior or a bug.
> The environment is fpc 2.6-bugfix branch x86-64 linux.
> See the details in the attached code
Your code is wrong: you have to assign the result of cm.create to an
interface variable instead of to a class instance variable. Created
class instances always have a reference count of 0 (both in FPC and in
Delphi). Only when assigning them to an interface, their reference
count gets increased.
Your "v as ip" expression increases the reference count to 1 since a
temporary interface variable is created to hold the result of that
expression. After the writeln is finished, that temporary variable
disappears and the reference count can go back to zero (that doesn't
happen immediately in either FPC or Delphi, but semantically at that
point the instance becomes invalid because it could be freed at any
time). Once the reference count becomes zero, the associated class
instance is freed. Anything that happens afterwards can crash, because
the instance is no longer valid.
It doesn't crash in Delphi because the details of when exactly it
decreases the reference count of the temporary expression is different
than in FPC. That is not something you can count on though.
Jonas
More information about the fpc-pascal
mailing list