Consider the case below
When we are using a C API's inside a class to create some data that are allocated in heap using malloc (e.g Object* create_obj()), and we have to call a certain method (void free_obj()) in the end of the class lifetime to free the memory manually.
When a language has a destructor, we can easily put the free_obj in the class destructor so the user does not have to call the free_obj manually and wait until the class get garbage collected.
My question
Why some garbage collected & OOP programming language (Java [Java has been deprecating it's
finalize] and Ruby) doesn't have a destructor?Isn't a destructor is necessary when you're interfacing a low level API like for the case above? If it's not necessary, what is the best practice to solve the problem below?
AutoCloseable. That interface has theclose()method which the developer is responsible for calling at the appropriate time. It was rarely, if ever, a good idea to rely onfinalize. And whilefinalizehas been deprecated they did addCleaner. But it's still best to avoid relying onCleaneras much as possible. For objects which don't hold open resources, and thus don't implementAutoCloseable, there's really no reason to have a destructor—the GC will take care of it.AutoCloseable, you don't needfinalizemalloc, so you don’t have a need to put a correspondingfreeinto a destructor.