Destructor not called when using New?

1
2
3
4
5
6
7
8
9
10
11
12

int main(){
SomeClass* classPTR = new SomeClass[5];
SomeClass MyClass;
return 0;
}

SomeClass:: ~SomeClass()
{
     cout << "Destructor called";
}


The destructor is only called once due the class created when I used
SomeClass MyClass;

But why is the destructor not called when I create the classes dynamically using

SomeClass* classPTR = new SomeClass[5];
Because you didn't delete it.
Last edited on
Ah I see thanks. So when I use new[], I have to manually delete it, unless new[] was used in some member function?
Last edited on
So when I use new[], I have to manually delete it


Sort of.

If you use new[], you must use delete[]
If you use new, then you must use delete.

1
2
SomeClass* classPTR = new SomeClass[5];
delete[] classPTR; // <- delete[] 


unless new[] was used in some member function?


No. ALWAYS. Every new[] must have a matching delete[]. Every new must have a matching delete. Failure to do this results in memory leaks.

You can avoid this by using smart pointers, which are basically classes the automatically call delete in their destructor. One such example is std::unique_ptr:

1
2
3
4
5
std::unique_ptr<SomeClass> p(new SomeClass);

p->whatever();

// no need to delete p because unique_ptr's dtor deletes it 


But unless you have some kind of container class like that, you must call delete yourself.
Topic archived. No new replies allowed.