为什么Java没有像C ++这样的析构函数? [英] Why does Java not have any destructor like C++?

查看:542
本文介绍了为什么Java没有像C ++这样的析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java有自己的垃圾收集实现,因此它不需要像C ++这样的任何析构函数。这使得Java开发人员懒得实现内存管理。

Java has its own garbage collection implementation so it does not require any destructor like C++ . This makes Java developer lazy in implementing memory management.

我们仍然可以使用析构函数和垃圾收集器,开发人员可以在其中释放资源,这可以节省垃圾收集器的工作。这可能会提高性能应用。为什么Java不提供任何析构函数的机制?

Still we can have destructor along with garbage collector where developer can free resources and which can save garbage collector's work. This might improves the performance of application. Why does Java not provide any destructor kind of mechanism?

开发人员无法控制GC,但他/她可以控制或创建对象。然后为什么不给他们破坏对象的能力呢?

Developer does not have control over GC but he/she can control or create object. Then why not give them ability to destruct the objects?

推荐答案

你断言垃圾收集非常昂贵 - 你能用证据支持吗?垃圾收集肯定不是免费的,但现代垃圾收集器非常好。

You're asserting that "garbage collection is very expensive" - could you back that up with evidence? Garbage collection is certainly not free but modern garbage collectors are very good.

请注意GC的一种方式高效的是它知道它是唯一做内存分配和释放的事情(对于托管对象)。允许开发人员显式释放对象可能会妨碍这种效率。如果开发人员试图使用一个释放的对象,你还需要担心会发生什么:

Note that one of the ways in which the GC is able to be efficient is that it knows it's the only thing doing memory allocation and deallocation (for managed objects). Allowing a developer to explicitly free an object could hamper that efficiency. You'd also need to worry about what would happen if a developer tried to "use" a freed object:

Foo f = new Foo();
Foo g = f;
free(f); // Or whatever
System.out.println(g.toString()); // What should this do?

您是否建议每个对象都应该有一个额外的标志明确释放了这个要检查每个解除引用?说实话,这感觉就像灾难一样。

Are you proposing that each object should have an extra flag for "has this explicitly been freed" which needs to be checked on every dereference? This feels like a recipe for disaster, to be honest.

你是对的 - 它确实允许Java开发人员在这个领域懒惰 >。这是好事。 IDE也允许开发人员变得懒惰 - 高级语言也是如此。等待内存分配的懒惰使得托管环境中的开发人员能够花费精力来解决业务问题而不是内存管理。

You're right though - it does allow Java developers to be lazy in this area. That's a good thing. IDEs allow developers to be lazy, too - as do high-level languages, etc. Laziness around memory allocation allows developers in managed environments to spend their energy worrying about business problems rather than memory management.

这篇关于为什么Java没有像C ++这样的析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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