为什么Go编译器会进行此优化

时间:2020-05-29 03:01:11

标签: go

package main

import (
    "fmt"
)

func main() {
    a := new(struct{})
    b := new(struct{})
    println(a, b, a==b)

    c := new(struct{})
    d := new(struct{})
    fmt.Println(c, d, c==d)
}

输出:

0xc000107f37 0xc000107f37 false
&{} &{} true

而且,在禁用编译器优化后,我会得到不同的结果。

0xc000087e4e 0xc000087e4e true
&{} &{} true

为什么Go编译器会进行此优化?

请参见[运行时源代码中的此行]

https://github.com/golang/go/blob/6317adeed7815ad335e2e97c463a7c3c4d82fc19/src/runtime/malloc.go#L586

    if size == 0 {
        return unsafe.Pointer(&zerobase)
    }

我认为,由于所有零大小的变量都将分配有零基,因此应该打印true而不是false。

0 个答案:

没有答案