似乎所有创建 ref 对象的示例都会创建一个副本或创建一个临时对象然后将其丢弃。如何创建对对象的引用,而不进行任何复制?我明确尝试在没有样式声明的情况下执行此操作type Rect = ref object...
。
看起来new Rect
是 类型ref Rect
。显然这进行了一些分配。
我见过的每个例子都大致如此:
type Rect = object
x: int
y: int
# Basic, no refs; create and assign
var r0: Rect = Rect(x:10, y:20)
# The usual example; this seems to create extra object, copy values, then throw away
var r1: ref Rect = new Rect # Creates default Rect
r1[] = Rect(x:10, y:20) # Create desired Rect, copy, and throw away first Rect
# Or Create desired Rect, assign, and throw away first Rect
# This is what I'd like to do. None of these attempts works
var r2: ref Rect = new Rect(x:10, y:20)
# Or this
var r3: ref Rect = ref Rect(x:10, y:20)
# Or this
var r4: ref Rect = ref new Rect(x:10, y:20)
# Or this
var r5: ref Rect = Rect(x:10, y:20)
那么,是否可以声明一个 ref 并将其分配给新实例,而无需复制和/或创建额外的一次性对象?最好在一行中完成此操作,但这不是硬性要求。
谢谢