在Nim中创建对数组的引用 [英] create a reference to an array in Nim
问题描述
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
在Nim中,如何将引用传递给数组而不是按值传递?到目前为止,请参阅上面的代码.
In Nim, how can I pass references to arrays instead of passing by value? See the above code for what I have so far.
推荐答案
在Nim中,ref
在堆上,必须使用new
进行分配.您不能仅将堆栈数组用作ref
,因为这是不安全的:当数组从堆栈中消失时,ref
指向某个错误的内存.相反,您有两个选择:您可以改用不安全的ptr
.除ref
外,它们不是垃圾收集的,可用于不安全的物品.或者,您可以直接将b
设置为ref array
.
In Nim ref
s 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 ptr
s instead. Other than ref
s, they are not garbage collected and can be used for unsafe stuff. Alternatively you can make b
a ref array
directly.
这篇关于在Nim中创建对数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!