返回指向本地结构的指针 [英] Return pointer to local struct

查看:141
本文介绍了返回指向本地结构的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类型点结构{
x,y int


func newPoint()* point {
return& point {10,20}
}

我有C ++背景,对我来说这似乎是错误的。这种结构的语义是什么?在堆栈或堆上分配新的点吗?

解决方案

Go执行指针逃逸分析。如果指针转义本地堆栈,则在此情况下,该对象将分配到堆上。如果它不能逃离本地函数,编译器可以自由地将它分配到堆栈上(尽管它不作任何保证;它取决于指针转义分析是否可以证明指针保持局部于该函数)


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?

解决方案

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).

这篇关于返回指向本地结构的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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