Re: [R] R.oo Destructors

From: Henrik Bengtsson <hb_at_stat.berkeley.edu>
Date: Thu 18 Jan 2007 - 01:43:24 GMT

Hi,

I'm about the head out of the office next 48 hours, but the short answer is to override the finalize() method in your subclass of Object. This will be called when R garbage collects the object. From ?finalize.Object:

 setConstructorS3("MyClass", function() {

    extend(Object(), "MyClass")
  })

  setMethodS3("finalize", "MyClass", function(this) {     cat(as.character(this), "is about to be removed from the memory!\n")   })

  o <- MyClass()
  o <- MyClass()
  o <- MyClass()
  o <- MyClass()

  gc()

  ## Not run:

MyClass: 0x31543776 is about to be removed from the memory!
MyClass: 0x31772572 is about to be removed from the memory!
MyClass: 0x32553244 is about to be removed from the memory!
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 246049  6.6     407500 10.9   350000  9.4
Vcells 132538  1.1     786432  6.0   404358  3.1

rm(o)
gc()

MyClass: 0x31424196 is about to be removed from the memory!

         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 246782  6.6     467875 12.5   354145  9.5
Vcells 110362  0.9     786432  6.0   404358  3.1

Hope this helps

Henrik

On 1/18/07, Feng, Ken [CIB-EQTY] <ken.feng@citigroup.com> wrote:
>
> Has anyone figured out how to create a destructor in R.oo?
>
> How I'd like to use it: I have an object which opens a connection thru RODBC
> (held as a private member) It would be nice if the connection closes automatically
> (inside the destructor) when an object gets gc()'ed.
>
> Thanks in advance.
>
> Regards,
> Ken
> BTW, a >BIG< thanks to Henrik Bengtsson for creating the R.oo package!
> Lucky for me as I am not smart enough to use S4...
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu Jan 18 12:49:27 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 18 Jan 2007 - 02:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.