Go可以保证常量地址吗? [英] Does Go guarantee constant addresses?

查看:58
本文介绍了Go可以保证常量地址吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个对象 obj 可以保证

uintptr(unsafe.Pointer(&obj))

无论何时调用,总是会得出相同的值?

will always evaluate to the same value regardless of when it is called?

当然,Go保证如果您使用两个指向同一对象的指针,它们将始终比较相等.尽管实现可能会在内存中移动对象并透明地更新指向该对象的所有指针.

Of course, Go guarantees that if you take two pointers to the same object, they will always compare equal. It might be possible though that an implementation moves an object in memory and transparently updates all pointers to it.

如果您考虑使用 Mark-and-Compact 这样的垃圾收集策略,这将很有趣.会允许实施者使用这种垃圾回收策略吗?

This is interesting if you consider garbage collection strategies like Mark-and-Compact. Would an implementor be allowed to use such a garbage collection strategy?

推荐答案

没有这样的保证,正是这样才可以实现移动的收集器.

There is no such guarantee, exactly so that it is possible to implement a moving collector.

事实上,尽管垃圾收集器今天不移动堆对象,但是在Go 1.3中,当需要增长时,堆栈可以移动,因此

In fact, although the garbage collector does not move heap objects today, in Go 1.3 stacks can move when needing to grow, so it is entirely possible that

var obj int
fmt.Println(uintptr(unsafe.Pointer(&obj)))
bigFunc()
fmt.Println(uintptr(unsafe.Pointer(&obj)))

将打印两个不同的指针,因为bigFunc增大了堆栈,导致obj和堆栈上的其他所有对象移动.

will print two different pointers, because bigFunc grew the stack, causing obj and everything else on the stack to move.

这篇关于Go可以保证常量地址吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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