亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

存儲指向堆棧值的指針(Golang)

存儲指向堆棧值的指針(Golang)

Go
慕尼黑5688855 2021-09-13 16:28:28
我正在嘗試在 Go 中進行實驗,看看如果我在堆棧上存儲一個指向變量的指針,然后在原始變量離開作用域后訪問該變量會發生什么。package mainimport "fmt"var p chan bool;// a temp structtype v struct {    a int}func another_thread(vx *v) {    // this code should be executed after a() returns so vx should be a pointer to a value that's no longer on the stack    fmt.Printf("another_thread(): %p\n", vx);    vx.a = 4 // am I updating a dangling pointer that may have unintentional side effects??    fmt.Println(" - ", vx.a);    p<-true;}func update_v(vx *v) {    vx.a = 3;    fmt.Printf("update_v(): %p\n", vx);    go another_thread(vx)}func alloc_on_stack() {    // allocate v1 on the stack    var v1 v    v1.a = 1    fmt.Printf("alloc_on_stack(): %p\n", &v1);    // pass a pointer to v1 on the stack    update_v(&v1)    // print '3' to prove byref actually took it by reference    fmt.Println(" - ", v1.a);    // when the function returns, v1 should be popped off the stack}func main() {    p = make(chan bool)    alloc_on_stack();    fmt.Println("outside of alloc_on_stack, waiting");    <-p;    fmt.Println("done");}在 alloc_on_stack 中,v1 作為局部變量存儲在堆棧上。我將指向 v1 的指針傳遞給 update_v,后者將其傳遞給 another_thread。由 another_thread 直到 alloc_on_stack 完成后才執行。然而,當我運行該代碼時,我沒有收到任何錯誤,而是看到了以下內容:alloc_on_stack(): 0x1043617cupdate_v(): 0x1043617c -  3outside of alloc_on_stack, waitinganother_thread(): 0x1043617c -  4doneanother_thread 中的 vx 不應該是一個懸空指針嗎?
查看完整描述

2 回答

?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

不。Go 編譯器檢測到您正在獲取局部變量的地址,并保留它,直到對它的所有引用都消失了。從那時起,該變量可以被垃圾收集。


這就是為什么這樣的東西不僅被允許,甚至是慣用的:


func foo() *Bar {

  return &Bar{42, "frob"}

}


查看完整回答
反對 回復 2021-09-13
  • 2 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號