在Nim中创建对数组的引用 [英] create a reference to an array in Nim

查看:102
本文介绍了在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 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.

这篇关于在Nim中创建对数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆