指向切片元素的一致性

huangapple go评论67阅读模式
英文:

Consistency of the pointer to a slice element

问题

考虑以下简单的代码示例:

s := make([]int, 0, 10<<20) // 创建一个包含1000万个int项的切片
s = append(s, 123456789)    // 追加任意随机数
p := &s[0]                  // 指向切片第一个元素的指针

// 添加新项。切片预计会在内存中重新分配。
for i := 0; i < 100<<20; i++ {
    s = append(s, i)
}

那么问题是:如果在追加操作(append())后切片"s"被重新分配,指针"p"是否也会指向切片"s"的新的第一个元素的地址?即"p"是否始终保存对值"123456789"的地址引用?还是需要重新创建指针?

提前感谢。

英文:

Consider the simple code sample:

s := make([]int, 0, 10&lt;&lt;20) // Create a slice with 10M int items
s = append(s, 123456789)    // Append any random number
p := &amp;s[0]                  // Pointer to a 1st element of the slice

// Adding new items. Slice expected to be re-allocated in the memory.
for i := 0; i &lt; 100&lt;&lt;20; i++ {
    s = append(s, i)
}

So, the question is: In case of slice "s" was re-allocated after append(), will pointer "p" also point to a new address of the 1st element of the slice "s" ? I.e. "p" always hold an address to the value "123456789". Or pointer need to be re-created?

Thanks in advance.

答案1

得分: 3

指针 p 将始终指向从第一个追加返回的 s 的第一个元素。连续的追加操作将创建新的数组,并将切片的内容复制到这些数组中,但是 p 将继续指向同一个数组的第一个元素。在中间的追加操作期间分配的数组将被垃圾回收,但是最后一个分配给 s 的数组和 p 指向的第一个数组只要 sp 保持活动状态,就不会被回收,因为它们有活动的引用。

英文:

Pointer p will always point to the first element of s that was returned from the first append. Consecutive appends will create new arrays and copy the contents of the slice to those arrays, but p will continue to point to the first element of the same array. The arrays allocated during the intermediate appends will be garbage collected, but the last one assigned to s, and the first one pointed to by p will not be as long as s and p are kept alive, because there are active references to them.

huangapple
  • 本文由 发表于 2023年3月7日 23:48:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75664200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定