Skip to content

Instantly share code, notes, and snippets.

@zacharycarter
Created October 8, 2018 16:07
Show Gist options
  • Save zacharycarter/21e7a121ae4ae18fc160d2b6e21b5f9e to your computer and use it in GitHub Desktop.
Save zacharycarter/21e7a121ae4ae18fc160d2b6e21b5f9e to your computer and use it in GitHub Desktop.
{.experimental.}
type Refcounted = ref object
rc: int
value: int
type A = object
r: Refcounted
proc newA(value: int): A =
result.r = Refcounted(value: value)
proc `=destroy`(a: A) =
echo "destroy ", (if a.r.isNil: "nil" else: $(a.r))
if not a.r.isNil:
dec a.r.rc
if a.r.rc == 0:
echo "destroy: ", a.r.value
proc `=`(lhs: var A, rhs: A) =
echo "assign from ", (if rhs.r.isNil: "nil" else: $(rhs.r)) , " to ", (if lhs.r.isNil: "nil" else: $(lhs.r))
if lhs.r != rhs.r:
`=destroy`(lhs)
lhs.r = rhs.r
if not lhs.r.isNil:
inc lhs.r.rc
proc testA(a: A) =
echo "testA 1"
var b = a
echo "testA 2"
block:
var v: A
block:
var v1 = newA(1)
var v2 = v1
testA(v2)
var v3 = v2
echo "Exiting scope 1"
v = v1
echo "Exiting scope 2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment