dongzhunnai0140 2015-12-17 10:58
浏览 29
已采纳

执行:函数返回指向内存的指针[重复]

This question already has an answer here:

I'm following the golang tour, this page: https://tour.golang.org/methods/3

package main

import (
    "fmt"
    "math"
)

type Vertex struct {
    X, Y float64
}

func (v Vertex) Scale(f float64) *Vertex {
    v.X = v.X * f
    v.Y = v.Y * f
    return &v //I'm returning a pointer to v
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
    v := &Vertex{3, 4}
    fmt.Printf("Before scaling: %+v, Abs: %v
", v, v.Abs())
    v = v.Scale(5) //I'm assiging it to v
    fmt.Printf("After scaling: %+v, Abs: %v
", v, v.Abs())
}

When i call v.Scale a copy of v is passed to the Scale function. Then, the Scale returns a pointer to the v that it has recevied.

Is this safe? Or will i end up with a sigsev at some point?

(Sorry for the title, but i couldn't think of a proper one feel free to edit it)

</div>
  • 写回答

1条回答 默认 最新

  • douqian2334 2015-12-17 11:04
    关注

    That's perfectly safe. When you call v.Scale, a copy of Vertex is allocated and you return a pointer to it. The copy won't be garbage collected as long as it's referenced to by the pointer. If the pointer goes out of scope (and can't be used anymore), the copy would be freed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用