2019-05-20 01:39 浏览 103

为什么`list.Remove()`试图显式避免内存泄漏? [重复]

This question already has an answer here:

The source code of container/list.Remove() tries to avoid memory leaks explicitly by assigning nil to specific variables, why should we do this? thanks!

The code is in the golang source code of version 1.12.

// remove removes e from its list, decrements l.len, and returns e.
func (l *List) remove(e *Element) *Element { = = e.prev = nil // avoid memory leaks
    e.prev = nil // avoid memory leaks
    e.list = nil
    return e

Can't GC handle this situation?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答 默认 最新

  • 已采纳
    dsgawmla208057 dsgawmla208057 2019-05-20 03:59

    An element removed from a list cannot be pointing to other elements in the list after its removal.

    Consider the list A -> B -> C -> D . And you remove the element B from the above list. Without the statement = nil

    in the code snipped above, the memory layout will look like this.

    A -> C > D

    Now if the element B is still in use(say element B is used till the end of the progarm), It has a pointer to C. This means that C cannot be garbage collected even if C is removed from list later and is not required for anymore.

    A similar case can occur for e.prev

    点赞 评论 复制链接分享