Golang新的内存分配

huangapple go评论89阅读模式
英文:

Golang new memory allocation

问题

我开始学习Go编程,我想知道当使用new(Object)时,它会为该对象分配内存,对吗?如果是这样,那么在我使用完对象后,如何释放这块内存呢?

我之所以问这个问题,是因为在C++中,当对一个对象使用new时,你可以在不再需要存储对象时使用delete来删除对象。

我一直在搜索是否Go语言有类似于C++的delete或类似的东西,但是我一直没有找到任何信息。

非常感谢任何帮助。

英文:

I have started programming in Go and I was wondering when new(Object) is used it allocates memory to the size of that object right? If this is the case how do I free this memory once I have finished using the object?

I ask this because in C++ when new is used on an object you can delete the object once there is no longer any need for the object to be stored.

I have been searching to see if Go does have delete or something similar to C++ but I have been unable to find anything.

Any help is much appreciated.

答案1

得分: 4

你可以在这里看到:

> Go是完全垃圾回收的,并且提供了对并发执行和通信的基本支持。

所以你不需要担心内存分配。

英文:

As you see here:

> Go is fully garbage-collected and provides fundamental support for concurrent execution and communication.

So you don't have to care about memory allocation.

答案2

得分: 3

Go语言具有垃圾回收功能。这意味着Go运行时会在后台检查对象或其他变量是否不再使用,如果是这种情况,就会释放内存。

还可以参考Go FAQ:为什么Go的语法与C语言如此不同?- 为什么要进行垃圾回收?难道不会太昂贵吗?

英文:

Go has garbage collection. This means the Go runtime checks in the background if an object or any other variable is not used anymore and if this is the case, frees the memory.

Also see the Go FAQ: Why is the syntax so different from C? - Why do garbage collection? Won't it be too expensive?

答案3

得分: 1

在Go语言中,与C和C++不同,但与Java类似,内存是由垃圾回收器自动管理的。

没有delete来调用。

离题:

> 在C++中,当对对象使用new时,一旦不再需要存储对象,可以delete该对象。

必须删除,否则会出现内存泄漏。

英文:

In Go, unlike in C and C++, but like in Java, memory is managed automatically by a garbage collector.

There is no delete to call.

Off-topic:

> in C++ when new is used on an object you can delete the object once there is no longer any need for the object to be stored.

You must delete, otherwise you have memory leak.

huangapple
  • 本文由 发表于 2016年10月24日 18:42:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/40216428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定