gpt4 book ai didi

arrays - 调用 append 后 slice 的行为是否定义明确?

转载 作者:IT王子 更新时间:2023-10-29 02:32:30 32 4
gpt4 key购买 nike

以下面的代码为例:

https://play.golang.org/p/vjux0TYz0D

看起来,根据 slice 持有的类型,append 有时会“复制”初始 slice (调用一个 append),而其他时候它会让它指向相同的底层数组。

是否定义了这种行为,假设代码:

a := []type{value1}
b := append(a, value2)

有没有办法知道在第二次操作后 a 和 b 是否指向同一内存?我可以以 100% 确定另一个未被修改的方式修改 a 或 b 吗? append 之后 'a' 可以指向一个完全不同的内存位置吗?在对其调用 append 之后,'a' 是否应该被视为具有未定义行为的垃圾?

最佳答案

语言规范说:

If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise, append re-uses the underlying array.

如果您希望 slice 指向不同的底层数组,您需要始终制作一个副本。

关于arrays - 调用 append 后 slice 的行为是否定义明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44588826/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com