从函数中的局部变量返回指针 [英] returning pointer from a local variable in function

查看:107
本文介绍了从函数中的局部变量返回指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本名为《 Go编程语言》的书,在有关指针的第二章中,写了以下内容

I'm reading a book called The Go Programming Language, and in the 2nd chapter about pointers the following is written

对于函数来说,返回局部变量的地址是绝对安全的.例如,在 在下面的代码中,由对f的特定调用创建的局部变量v将仍然存在 调用返回后,指针p仍将引用它:

It is perfectly safe for a function to return the address of a local variable. For instance, in the code below, the local variable v created by this particular call to f will remain in existence even after the call has returned, and the pointer p will still refer to it:

var p = f()
func f() *int {
    v := 1
    return &v
}

我完全不明白这一点,应该在执行函数后销毁局部变量.是因为可能v是在堆上分配的.我知道在C语言中,如果您使用malloc分配空间,函数执行后就不会销毁它,因为它在堆上.

I totally don't get this, a local variable is supposed to be destroyed after the function execution. Is it because maybe v is allocated on the heap. I know in C if you allocate space using malloc it won't be destroyed after function execution because it's on the heap.

推荐答案

Go不是C.尽管有相似之处,但它的层次更高.它利用了带有绿色线程调度程序和垃圾收集内存管理器的完整运行时.只要有实时引用,它就永远不会收集内存.

Go isn't C. Despite similarities, it is much higher-level. It utilizes a complete runtime with a green thread scheduler and garbage-collecting memory manager. It will never collect memory so long as it has live references.

Go编译器包括一个称为转义分析"的阶段,在该阶段中,它跟踪每个变量以查看其是否转义"了声明其的函数.任何可以转义的值都在堆上分配,并由垃圾回收管理.否则,它(通常)分配在堆栈上.

The Go compiler includes a stage called "escape analysis", where it tracks each variable to see if it "escapes" the function in which it is declared. Any value that can escape is allocated on the heap and managed by garbage collection; otherwise, it is (usually) allocated on the stack.

您可以找到有关该主题的更多信息:

You can find more information on the subject:

  • https://blog.golang.org/ismmkeynote
  • https://dave.cheney.net/2014/06/07/five-things-that-make-go-fast
  • https://dougrichardson.org/2016/01/23/go-memory-allocations.html
  • https://www.agardner.me/golang/garbage/collection/gc/escape/analysis/2015/10/18/go-escape-analysis.html
  • https://www.ardanlabs.com/blog/2017/05/language-mechanics-on-escape-analysis.html

这篇关于从函数中的局部变量返回指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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