ClassyPimp
ClassyPimp

Reputation: 725

Crystal lang, is it possible to explicitly dispose (free) of instance (object) without waiting for GC?

The title says it all. Maybe there's a method can be called like def destruct; delete self;end?

Upvotes: 6

Views: 450

Answers (1)

asterite
asterite

Reputation: 2926

It's possible, but definitely not recommended and the way I'll show you might change or break in the future. Why do you need this? The idea of a GC is precisely not worrying about such things.

class Foo
  def initialize
    @x = 10
  end

  def finalize
    puts "Never called"
  end
end

foo = Foo.new
p foo # => #<Foo:0x10be27fd0 @x=10>
GC.free(Pointer(Void).new(foo.object_id)) # This line frees the memory
p foo # => #<Foo:0x10be27fd0 @x=1>

Upvotes: 7

Related Questions