Doubt about function in C ++ that works as a destructor? [closed]

1

I understood all the code below but in certain part the person quotes something as a destructor? What is it? What's the use?

It would be this part here:

~Vetor() {
    delete [] vet_pos;
    delete [] vet;  }

Why is this ~ next to the function? More looks like a builder!

// Sobrecarregando o operador de índice: []

#include <iostream>
#include <stdlib.h> // função exit()
using namespace std;

class Vetor
{
private:
    int *vet, *vet_pos;
    int max;

public:
    Vetor(int max = 100)
    {
        if(max < 0)
        {
            cerr << "Erro: limite maximo menor do que 0." << endl;
            exit(1);
        }
        else if(max > 1000000)
        {
            cerr << "Erro: limite maximo maior do que 1000000." << endl;
            exit(1);
        }

        this->max = max;

        // alocar espaço
        vet = (int*)malloc(max * sizeof(int));
        vet_pos = (int*)malloc(max * sizeof(int));

        for(int i = 0; i < max; i++)
            vet_pos[i] = 0;
    }


    ~Vetor()
    {
        delete [] vet_pos;
        delete [] vet;
    }


    bool inserir(int e, int pos)
    {
        if(pos < max && pos >= 0)
        {
            vet[pos] = e;
            vet_pos[pos] = 1;
            return true;
        }
        return false;
    }


    int& operator[](int i)
    {
        if(i < 0 || i >= max)
        {
            cerr << "Erro: acesso invalido ao vetor.\n";
            exit(1);
        }
        else if(vet_pos[i] == 0)
        {
            cerr << "Erro: nessa posicao nao existe elemento.\n";
            exit(1);
        }
        return vet[i];
    }



    int tam()
    {
        int cont = 0;

        for(int i = 0; i < max; i++)
        {
            if(vet_pos[i] == 1)
                cont++;
        }
        return cont;
    }
};

int main(int argc, char *argv[])
{
    Vetor v(10);

    if(v.inserir(10, 0))
        cout << "Elemento inserido com sucesso!\n";
    else
        cout << "Erro ao inserir o elemento.\n";

    if(v.inserir(11, 2))
        cout << "Elemento inserido com sucesso!\n";
    else
        cout << "Erro ao inserir o elemento.\n";

    if(v.inserir(12, 10))
        cout << "Elemento inserido com sucesso!\n";
    else
        cout << "Erro ao inserir o elemento.\n";

    cout << "Primeiro elemento: " << v[0] << endl;
    cout << "Segundo elemento: " << v[2] << endl;
    //cout << "Terceiro elemento: " << v[2] << endl;

    return 0;
}
    
asked by anonymous 25.10.2018 / 21:24

2 answers

3

C ++ is a language that gives freedom to do powerful and flexible things. And with this requires a lot of responsibility to manage all the resources.

When you instantiate an object there are basically two operations: the allocation made by the new operator, and this can be customized in the type it is creating with operator overload; and the construct that is customized in constructor methods , which are static methods, that is, they are part of the type and will initialize the data in the object being created. In addition to data initialization you can run certain algorithms and work with external resources to the application, such as operating system services for example.

This object has a lifetime determined by a number of factors. At the moment the object should cease to exist if it has a destructor method it is called (it is placed by the compiler in the appropriate location, either invoked by the library or manually called by the programmer). This is a method, which is virtual, can, or even must, release externally acquired resources, execute some termination algorithms, and free the allocated memory through delete ". Failure to do so will have "hanging" features and memory leaks . So without this method or without it doing the proper operations you will have problems.

The ~ prefixed in the name was agreed to be the destructor, just to differentiate it from the constructor that has the type name equal to the destructor.

In his example he is releasing the memory of two vectors. But this code is poorly done. Never allocate by one method and release by another. In case it was allocated with malloc() , then you should use free() . Or else it should have allocated with new to release with delete which is the most correct in C ++. Even the most C ++-like part uses a 90's style, C ++ has changed a lot. The code was written by someone who does not understand C ++ right.

See When the destructor of an object is called in C ++? . Or in a more abstract context than they are: What is a destructor for? .

    
25.10.2018 / 21:41
0

Briefly:

The destructor is the opposite of the constructor.

While a constructor function of a given class is called the moment an instance of that class is created (object), the destructor function is called when the object is destroyed.

For more details, read Maniero's answer, which is always more complete!

    
25.10.2018 / 22:01