I Need to Call delete[] on a Dynamic Array within a Class but It Doesn't Work

Viewed 71

I wrote code very similar to this (although not identical) for a game I'm making. This has the same issue, so I'll provide it.

#include <iostream>

using namespace std;

class test {
public:
    int* arr;
    test(int n) {
        arr = new int[n];
        for(int i=0; i<=9; i++) {
            arr[i] = i;
        }
    }
    ~test() {
        delete[] arr;
    }
};

int main() {

    test obj = test(10);
    for(int i=0; i<=8; i++) {
        cout << obj.arr[i] << endl;
    }
    cout << obj.arr[9];
    obj.~test();
    return 0;

}

I know that I could rework my code and use the vector class to avoid this problem, but I want to actually understand why it's crashing. Removing the deconstructor call fixes the error, but that also introduces a memory leak, so I would prefer to just fix the deconstructor.

3 Answers

This line is causing the error:

obj.~test(); // removing this will solve your problem

You shouldn't call the destructor. Once the object goes out of scope the destructor will get called.

You are explicitly calling the ~test() destructor on your obj variable, and then that same destructor will be implicitly called again when obj goes out of scope afterwards. Omitting the explicit destructor will NOT cause a memory leak. Let the compiler call the destructor for you. The ONLY time you can ever safely call a destructor explicitly is when the object being destructed was constructed using placement-new, which is not the case in your example.

Just adding to the first answer that aptly notes that manual destructor invocation is errorneous here, I will also note that

class test {
public:
    int* arr;
    test(int n) {
        arr = new int[n];
        /* Redacted fro brevity */
    }
    ~test() {
        delete[] arr;
    }
};

has default copy-ctor and assignment operator. Those operators will crash the program and also leak the memory. Special copy-ctor, move-ctor, etc. should be defined in this context to provide proper memory management.

Even better, use std::vector that does that automatically.

Related