Destructor in structures

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
User_Russian
Addict
Addict
Posts: 1443
Joined: Wed Nov 12, 2008 5:01 pm
Location: Russia

Destructor in structures

Post by User_Russian »

I propose to add a destructor to the structure. What is it for? PB can automatically free up structures containing arrays, lists, etc. But if the structure has a pointer to memory, or ID file, image and etc., they will not be released. It is necessary to provide for a procedure call when the structure is released.
Here is a small example.

Code: Select all

Declare FreeStrX(*This)
Declare FreeStrY(*This)

Structure y
  *Point
  File.i
  Image.i
  
  Destructor FreeStrY()
EndStructure

Structure x
  *Struct
  Mutex.i
  List l.y()
  
  Destructor FreeStrX()
EndStructure

Procedure FreeStrX(*This.X)
  If *This\Struct
    FreeStructure(*This\Struct)
    *This\Struct=0
  EndIf
  
  If *This\Mutex
    FreeMutex(*This\Mutex)
    *This\Mutex=0
  EndIf
EndProcedure

Procedure FreeStrY(*This.Y)
  If *This\Point
    FreeMemory(*This\Point)
    *This\Point=0
  EndIf
  
  If *This\File And IsFile(*This\File)
    CloseFile(*This\File)
    *This\File=0
  EndIf
  
  If *This\Image And IsImage(*This\Image)
    FreeImage(*This\Image)
    *This\Image=0
  EndIf
EndProcedure


Procedure Test()
  Protected s.x
  
  s\Struct = AllocateStructure(y)
  s\Mutex = CreateMutex()
  
  For i=1 To 10
    If AddElement(s\l())
      s\l()\Point = AllocateMemory(100)
      s\l()\File = OpenFile(#PB_Any, "File"+i)
      s\l()\Image = CreateImage(#PB_Any, 10, 10)
    EndIf
  Next
  
EndProcedure


Test()
End
Note that in the procedure Test(), files, images, etc. are created, but they are not released in it. This is done in procedures FreeStrX() and FreeStrY().
The procedure FreeStrY() will be called 11 times (1 time from the procedure FreeStrX() when calling the function FreeStructure() and called 10 when implicitly freeing structures from the list s\l()).
Procedure FreeStrX() will be called once, with the implicit release of the structure X when the Test() procedure is completed.

It may also make sense to add a constructor to the structures.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Re: Destructor in structures

Post by Mistrel »

I would argue that PureBasic structures are purely on the stack but they do act more like objects now that they handle freeing lists and maps.
Post Reply