Skip to content

Instantly share code, notes, and snippets.

@wu-lee
Created April 4, 2018 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wu-lee/704d66367e1466ff763b332b393e1863 to your computer and use it in GitHub Desktop.
Save wu-lee/704d66367e1466ff763b332b393e1863 to your computer and use it in GitHub Desktop.
faulty cloning in nim
type
# ...
Vector*[T] = object
x*, y*: T
Animatable* = object of RootObj
Ball* = object of Animatable
pos*: Vector[float]
method clone*(anim: Animatable): ref Animatable {.base.} =
raise
method badclone*(anim: Animatable): ref Animatable {.base.} =
raise
# this makes a bad (incomplete) copy
method badclone*(ball: Ball): ref Animatable =
result.new
result[].deepCopy(ball)
# This works
method clone*(ball: Ball): ref Animatable =
var ball2 = new Ball
ball2[].deepCopy(ball)
result = ball2
var
ball = Ball(pos: Vector[float](x: 111, y: 999))
goodball = ball.clone
badball = ball.badclone
echo repr ball
echo repr goodball
echo repr badball
discard """output:
nim c -r --verbosity\:0 --hint\[Processing\]\:off --excessiveStackTrace\:on /home/nick/i/gitworking/noofac/nim-bounce/scratch.nim
[pos = [x = 111.0,
y = 999.0]]
ref 0x7f13067e8048 --> [pos = [x = 111.0,
y = 999.0]]
ref 0x7f13067e9048 --> [pos = [x = 1.531603502107864e-322,
y = 0.0]]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment