closureleak.nim 750 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. discard """
  2. outputsub: "true"
  3. disabled: "32bit"
  4. """
  5. type
  6. TFoo* = object
  7. id: int
  8. fn: proc() {.closure.}
  9. var foo_counter = 0
  10. var alive_foos = newseq[int](0)
  11. when defined(gcDestructors):
  12. proc `=destroy`(some: var TFoo) =
  13. alive_foos.del alive_foos.find(some.id)
  14. `=destroy`(some.fn)
  15. else:
  16. proc free*(some: ref TFoo) =
  17. #echo "Tfoo #", some.id, " freed"
  18. alive_foos.del alive_foos.find(some.id)
  19. proc newFoo*(): ref TFoo =
  20. when defined(gcDestructors):
  21. new result
  22. else:
  23. new result, free
  24. result.id = foo_counter
  25. alive_foos.add result.id
  26. inc foo_counter
  27. for i in 0 ..< 10:
  28. discard newFoo()
  29. for i in 0 ..< 10:
  30. let f = newFoo()
  31. f.fn = proc =
  32. echo f.id
  33. GC_fullcollect()
  34. echo alive_foos.len <= 3