默认情况下,Go 中哪些对象是最终确定的?它有哪些陷阱?
The function runtime.SetFinalizer(x, f interface{})
sets the finalizer associated with x
to f
.
What kind of objects are finalized by default?
What are some of the unintended pitfalls caused by having those objects finalized by default?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
默认情况下最终确定以下对象:
os.File
:当对象被垃圾回收时,文件会自动关闭。os.Process
:最终确定将释放所有资源与流程相关。在 Unix 上,这是一个空操作。在 Windows 上,它关闭与进程关联的句柄。在 Windows 上,包
net
似乎可以自动关闭网络连接。Go 标准库不会对上述以外的对象类型设置终结器。
似乎只有一个潜在问题可能会导致实际程序出现问题:当 os.File 完成时,它将调用操作系统来关闭文件描述符。如果 os.File 是通过调用函数 os.NewFile(fd int, name string) *File 创建的,并且文件描述符也被另一个(不同的)使用
os.File
,则垃圾收集其中一个文件对象将使另一个文件对象无法使用。例如:打印:
The following objects are finalized by default:
os.File
: The file is automatically closed when the object is garbage collected.os.Process
: Finalization will release any resources associated with the process. On Unix, this is a no-operation. On Windows, it closes the handle associated with the process.On Windows, it appears that package
net
can automatically close a network connection.The Go standard library is not setting a finalizer on object kinds other than the ones mentioned above.
There seems to be only one potential issue that may cause problems in actual programs: When an
os.File
is finalized, it will make a call to the OS to close the file descriptor. In case theos.File
has been created by calling functionos.NewFile(fd int, name string) *File
and the file descriptor is also used by another (different)os.File
, then garbage collecting either one of the file objects will render the other file object unusable. For example:prints:
只需跳转到 os.NewFile 的源代码:
Just jump into the os.NewFile's source code:
“默认情况下,什么类型的对象是最终确定的?”
在 IMO 中,Go 中的任何内容都不是默认最终确定的。
“默认情况下完成这些对象会导致哪些意外陷阱?”
如上所述:没有。
"What kind of objects are finalized by default?"
Nothing in Go is IMO finalized by default.
"What are some of the unintended pitfalls caused by having those objects finalized by default?"
As per above: none.