create a reference to an array in Nim

对着背影说爱祢 提交于 2019-12-07 01:47:06

问题


var b: array[5, int]

type
    ArrRef = ref array[5, int]

var c : ArrRef
echo repr(c) # nil
c = addr b # doesn't compile, says type is Array constructor, expected reference

In Nim, how can I pass references to arrays instead of passing by value? See the above code for what I have so far.


回答1:


In Nim refs are on the heap and have to be allocated with new. You can't just use a stack array as a ref because that would be unsafe: When the array disappears from the stack, the ref points to some wrong memory. Instead you have two choices: You can use unsafe ptrs instead. Other than refs, they are not garbage collected and can be used for unsafe stuff. Alternatively you can make b a ref array directly.



来源:https://stackoverflow.com/questions/30584140/create-a-reference-to-an-array-in-nim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!