Cannot make work finalizer


#1

I can’t make work the finalizer. I have this type A :

type A
  i::Int64
  function A(i::Int64)
    a = new(i)
    println("typeof(a) = $(typeof(a))")
    println("constructor $(a.i)")
    finalizer(a, destructor)
  end
end
destructor(a::A) = println("destructor $(a.i)") 

And when I instanciate a = A(1), I get those errors :

typeof(a) = A
constructor 1
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF
jl_uv_writecb() ERROR: bad file descriptor EBADF


#2
  1. You are not actually returning anything from the constructor so a is nothing
  2. You cannot print (or do any task switch) in finalizer, you should be able to see this warning message if you let the finalizer run before other part of the system shuts down.

#3

Hi yuyichao,
Sorry, I don’t get it. I would like to have this destructor prints things at the end of a scope. Can’t I do this way? Do I have to explicitly call a function at the end of a scope?


#4

No you cannot use normal print functions in finalizers. On master/0.6, Core.println etc should work but it doesn’t use the Base show functions so you can format the string yourself and call Core.println.

Also note that the finalizer will not be run at the end of a scope. It can be run before or after that, whenever the runtime determines that the value will not be used again.


#5

Ok, thanks. In Julia, is there any other mechanisms to execute some code automatically at the end of a scope (like a destructor in c++) ?


#6

No, but you can use macros or function wrappers (see the do syntax for anonymous function) to enforce that.


#7

Thanks