What is a destructor for?

7

In some languages, classes have methods destructors .

In the ones I've seen, it's declared as a constructor with the ~ sign on the front. Something like:

public class Foo
{
    public ~Foo()
    {
        //Fazer algo
    }
}

What are destructor methods used for? What is the need to create them?

    
asked by anonymous 20.07.2015 / 13:28

2 answers

3

Destrutores methods serve to release the memory allocated dynamically by the class, to eliminate references to it, when it does not exist.

In programming languages that have Garbage Collector , it is not necessary to use destructor methods, because Garbage Collector is in charge of doing this.

The need to create them, is in cases where the language does not have Garbage Collector , and it becomes necessary to destroy the class after its use, so that it does not occupy memory.

In languages that have Garbage Collector , only use is necessary when using unmanaged resources.

  

Most common types of unmanaged resources are objects that involve features of the operating system, such as files, windows, network connections, or database connections. Microsoft

In these cases Garbage Collector does not know how to release and clean the unmanaged resource.

Not all languages use the ~ sign to designate a destructor.

In PHP , for example, __ is used:

void __destruct ( void )

Python

def __del__(self):
    
20.07.2015 / 13:38
0

They are special methods that contain clean code for the object. You can not call them explicitly in your code, as they are called implicitly by the GC. In C # they even have the name of the class preceded by the ~ sign. Example:

class MyClass{

~ MyClass(){
.....
  }
}

In VB.NET, destructors are implemented by overriding the Finalize method of the System.Object class.

Why use?

  

When you write objects that manipulate non-resource   managed [To destroy unmanaged resources]

    
20.07.2015 / 13:36