Recent

Author Topic: Temporary Managed Value - Lifespan  (Read 320 times)

Warfley

  • Sr. Member
  • ****
  • Posts: 303
Temporary Managed Value - Lifespan
« on: May 29, 2020, 07:17:50 pm »
Hey, while working on some managed types using management operators, I've found something interesting out. Temporary values of managed objects get destroyed at the end of the enclosing function.

Example:
TGUniqueObject is a record implementing the management operators that frees an object on the Finalize operator. It also has an overloaded Implicit operator to the class type. For this test I also let it print out free whenever it frees an object:
Code: Pascal  [Select][+][-]
  1. program example;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. uses
  6.   heaptrc, Classes, uniqueobject;
  7.  
  8. type
  9.   TUniqueSL = specialize TGUniqueObject<TStringList>;
  10.  
  11. procedure Foo;
  12. var
  13.   s: TStringList;
  14. begin
  15.   s := TUniqueSL.Create(TStringList.Create);
  16.   s.Add('test');
  17.   WriteLn(s.Text);
  18. end;
  19.  
  20. begin
  21.   foo;
  22.   WRiteln('end');
  23. end.    

Result:
Code: Text  [Select][+][-]
  1. test
  2.  
  3. free
  4. end

So the free gets called after the procedure foo exits and not after the memory object in question (the temporary TUniqueSL instance) gets "out of scope" (i.e. is not accessible anymore).
This of course has the neat side effect that using this code above I can create temporary instances without the need of using a variable of type TUniqueSL, which will automatically get cleaned up.

So I have a question about this: Is this intended behavior and can I rely on this, or is this a side effect that might change in the future?

Jonas Maebe

  • Hero Member
  • *****
  • Posts: 757
Re: Temporary Managed Value - Lifespan
« Reply #1 on: May 29, 2020, 09:24:10 pm »
So I have a question about this: Is this intended behavior and can I rely on this, or is this a side effect that might change in the future?
It's an implementation detail. It can indeed change in the future, possibly depending on optimisation level.

Warfley

  • Sr. Member
  • ****
  • Posts: 303
Re: Temporary Managed Value - Lifespan
« Reply #2 on: May 30, 2020, 06:41:35 pm »
Ok, thank you

 

TinyPortal © 2005-2018