M_T
M_T

Reputation: 71

Heap - constructor and destructor, memory allocation

I have a class with constructor and destructor and one other method. When i create new instance of this class then it calls destructor somewhere and I dont know why.

class Heap
{
private:
    int *heap;
    int size;
    int heap_size;
public:
    Heap(int new_size)
    {
        size = new_size;
        heap_size = 0; 
        heap = (int*)malloc(new_size*sizeof(int)); //??? 
        //heap = new int[new_size]; //???
    }
    ~Heap()
    { 
        free(heap);
    }
    void add(int alfa)
    {
    // something
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    srand(time(NULL));
    int k = rand() % 100 + 1;
    Heap *name = &Heap(k);
    Heap *name2 = new Heap(k); //what's the diffrence?
    while (k > 0)
    {
        name->add(rand()); // doesn't work, because destructor is called before
        k--;
    }
    system("pause");
    return 0;
}

Upvotes: 1

Views: 2274

Answers (1)

juanchopanza
juanchopanza

Reputation: 227390

In the process running this non-standard piece of code1, which would most likely produce undefined behaviour2 anyway, this line

Heap *name = &Heap(k);

produces a temporary Heap object that gets destroyed at the end of that full expression. This results in the destructor being called.

Note that the fact remains that your class is quite fragile because it does not follow the rule of three (five). Copying Heap objects would lead to double-deletes.


1 For good reasons, standard C++ does not allow to take the address of a temporary.
2 This construction leaves you with a dangling pointer. Technically, de-referencing name is what would cause undefined behaviour.

Upvotes: 3

Related Questions