Question about a C++ function that functions as a destructor?

Asked

Viewed 297 times

1

I understood all the code below but in a certain part the person cites something as destructor? What is it? What is it for?

That would be the part here:

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

Because there’s this ~ next to the function? More like a constructor!

// 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;
}

2 answers

3


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

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

This object has a lifespan determined by a number of factors. At the moment the object must cease to exist if it has one destructor method it is called (it is placed by the compiler in the proper place, or is invoked by the library or manually called by the programmer). This is method, which is virtual, can, or even should, free externally acquired resources, run some completion algorithms and free up the allocated memory through the delete. If you don’t do this you will have "hanging" resources and memory leak. So without this method or without it doing the proper operations you will have problems.

The ~ as prefix in the name was agreed to be the destructor, only to differentiate 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 badly done. Never allot for one method and release for another. In the case it was allocated with malloc(), then you should use free(). Or else 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 from there to here. The code was written by someone who doesn’t understand C++ right.

Behold When the destroyer of an object is called in C++?. Or in a more abstract context than they are: What good is a destroyer?.

  • Thank you Maniero, your reply made me understand how the whole process works correctly.

  • But just to conclude, the destructor only happens to be destructor if it comes preceded by ~ before the method ? Of course you need to delete inside the method to work but that question still remains. Thanks again.

0

Briefly:

The destructor is the opposite of the constructor.

While a constructor function of a given class is called at 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 reply, which is always more complete!

  • Thanks Peter for the help :)

  • The C++ language is very broad and I always discover new things that help you understand more about how programming works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.