tdestructor3.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. discard """
  2. output: '''
  3. assign
  4. destroy
  5. destroy
  6. 5
  7. 123
  8. destroy Foo: 123
  9. destroy Foo: 5
  10. (x1: (val: ...))
  11. destroy
  12. ---------------
  13. app begin
  14. (val: ...)
  15. destroy
  16. app end
  17. '''
  18. joinable: false
  19. """
  20. # bug #2821
  21. type T = object
  22. proc `=`(lhs: var T, rhs: T) =
  23. echo "assign"
  24. proc `=destroy`(v: var T) =
  25. echo "destroy"
  26. proc use(x: T) = discard
  27. proc usedToBeBlock =
  28. var v1 = T()
  29. var v2: T = v1
  30. discard addr(v2) # prevent cursorfication
  31. use v1
  32. usedToBeBlock()
  33. # bug #1632
  34. type
  35. Foo = object of RootObj
  36. x: int
  37. proc `=destroy`(a: var Foo) =
  38. echo "destroy Foo: " & $a.x
  39. template toFooPtr(a: int{lit}): ptr Foo =
  40. var temp = Foo(x:a)
  41. temp.addr
  42. proc test(a: ptr Foo) =
  43. echo a[].x
  44. proc main =
  45. test(toFooPtr(5))
  46. test(toFooPtr(123))
  47. main()
  48. # bug #11517
  49. type
  50. UniquePtr*[T] = object
  51. val: ptr T
  52. proc `=destroy`*[T](p: var UniquePtr[T]) =
  53. mixin `=destroy`
  54. echo "destroy"
  55. if p.val != nil:
  56. `=destroy`(p.val[])
  57. dealloc(p.val)
  58. p.val = nil
  59. proc `=`*[T](dest: var UniquePtr[T], src: UniquePtr[T]) {.error.}
  60. proc `=sink`*[T](dest: var UniquePtr[T], src: UniquePtr[T]) {.inline.} =
  61. if dest.val != src.val:
  62. if dest.val != nil:
  63. `=destroy`(dest)
  64. dest.val = src.val
  65. proc newUniquePtr*[T](val: sink T): UniquePtr[T] =
  66. result.val = create(T)
  67. result.val[] = val
  68. #-------------------------------------------------------------
  69. type
  70. MyObject = object of RootObj
  71. x1: UniquePtr[int]
  72. MyObject2 = object of MyObject
  73. proc newObj2(x:int, y: float): MyObject2 =
  74. MyObject2(x1: newUniquePtr(x))
  75. proc test =
  76. let obj2 = newObj2(1, 1.0)
  77. echo obj2
  78. test()
  79. #------------------------------------------------------------
  80. # Issue #12883
  81. type
  82. TopObject = object
  83. internal: UniquePtr[int]
  84. proc deleteTop(p: ptr TopObject) =
  85. if p != nil:
  86. `=destroy`(p[]) # !!! this operation used to leak the integer
  87. deallocshared(p)
  88. proc createTop(): ptr TopObject =
  89. result = cast[ptr TopObject](allocShared0(sizeof(TopObject)))
  90. result.internal = newUniquePtr(1)
  91. proc test2() =
  92. let x = createTop()
  93. echo $x.internal
  94. deleteTop(x)
  95. echo "---------------"
  96. echo "app begin"
  97. test2()
  98. echo "app end"