英文:
Return pointer to local struct
问题
我看到一些代码示例,其中有这样的结构:
type point struct {
x, y int
}
func newPoint() *point {
return &point{10, 20}
}
我有C++背景,这对我来说似乎是错误的。这种结构的语义是什么?新的point是在堆上还是栈上分配的?
英文:
I see some code samples with constructs like this:
type point struct {
x, y int
}
func newPoint() *point {
return &point{10, 20}
}
I have C++ background and it seems like error for me. What are the semantic of such construct? Is new point allocated on the stack or heap?
答案1
得分: 132
Go执行指针逃逸分析。如果指针逃逸了本地堆栈,就像在这个例子中一样,对象将在堆上分配。如果它没有逃逸本地函数,编译器可以自由地在堆栈上分配它(尽管它不提供任何保证;这取决于指针逃逸分析是否能证明指针仍然局限于该函数)。
英文:
Go performs pointer escape analysis. If the pointer escapes the local stack, which it does in this case, the object is allocated on the heap. If it doesn't escape the local function, the compiler is free to allocate it on the stack (although it makes no guarantees; it depends on whether the pointer escape analysis can prove that the pointer stays local to this function).
答案2
得分: 21
Golang的“文档说明返回指向局部变量的指针是完全合法的。”根据我在这里阅读的内容,https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/EYUuead0LsY,编译器似乎会看到你返回的地址,并为你在堆上创建它。这是Go语言中常见的习惯用法。
英文:
The Golang "Documentation states that it's perfectly legal to return a pointer to local variable." As I read here
https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/EYUuead0LsY
I looks like the compiler sees you return the address and just makes it on the heap for you. This is a common idiom in Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论