2012-02-22 36 views
1

I am currently studying this piece of code.這是一個用Ruby實現的鏈表。 我對這兩種方法特別感興趣。適當的垃圾收集與Ruby中的鏈接列表?

def removeLast 
    if @size <= 0 
     raise "No objects in list" 
    end 

    node = @last.prev 
    node.prev.next = @last 
    @last.prev = node.prev 
    @size -= 1 

    return node.object 
end 

def removeFirst 
    if @size <= 0 
     raise "No objects in list" 
    end 

    node = @first.next 
    node.next.prev = @first 
    @first.next = node.next 
    @size -= 1 

    return node.object 
end 

這兩個方法從列表中刪除並返回一個節點。我不確定Ruby如何處理垃圾收集。您會注意到這兩種方法都不會明確銷燬他們嘗試刪除的節點。

Ruby是否足夠聰明,可以從內存中釋放這個刪除節點,而不必明確告訴它這樣做?

如果不夠,我該如何正確銷燬已移除的節點並釋放內存?

回答

2

當垃圾收集器運行時,它會看到node不再被應用程序中的對象引用,它將被釋放。

您不需要手動銷燬它。

+0

不知道Ruby是聰明!謝謝 – 2012-02-22 18:58:03

1

更明確地說:

@list = ... # initialize and fill out the list 

def remove_and_print_last(list) 
    last = list.removeLast # 'last' is only one reference to the object and 
    puts last    # reference will be invalid out of method 
end 

remove_and_print_last(@list) 

# here's no reference to last element, so if garbage collector would run here 
# gc will free this place by adding it to the freelist