Why does Java not have any destructor like C++? [c

2019-03-10 08:06发布

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.

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?

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?

10条回答
疯言疯语
2楼-- · 2019-03-10 08:17

The C++ destructor is not a way to destruct objects - it's a set of operation that are to be done when the object is destructed.

I think you are confusing terminology. Here is how I see it:

create object = first allocate memory, then construct via constructor

destroy object = first destruct via destructor, then deallocate memory

How the memory is allocated and deallocated depends. If you use new and delete, the memory management is done by void* operator new(size_t) and void operator delete(void*).

查看更多
手持菜刀,她持情操
3楼-- · 2019-03-10 08:26

If you know you don't some big objects anymore just set the references to them to null. This could maybe speed up the garbage collection of these objects.

查看更多
Luminary・发光体
4楼-- · 2019-03-10 08:31

Destructors are called when the object is destroyed in C++, not to destroy the object. If you want to guarantee cleanup, make the user call a Destroy method or similar.

查看更多
Anthone
5楼-- · 2019-03-10 08:31

No, java does not support destructors. All freeing the memory task is done by GARBAGE COLLECTOR.

Java has it's own memory management feature using garbage collector. When you use finalize() the object becomes available for garbage collection and you don't need to explicitly call for the destructor. C# and Java don't want you to worry about destructor as they have feature of garbage collection.

Java is a bytecode language, it has very strong garbage detection. If you were to allow people to define their own destructors it is likely that they might make some mistakes. By automating the process, Java intends to prevent those mistakes.

查看更多
登录 后发表回答