Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A destructor - should I use delete or delete[]?

I am writing a template class that takes as an input a pointer and stores it. The pointer is meant to point to an object allocated by another class, and handed to the this containing class.

Now I want to create a destructor for this container. How should I free the memory pointed to by this pointer? I have no way of knowing a priori whether it is an array or a single element.

I'm sort of new to C++, so bear with me. I've always used C, and Java is my OO language of choice, but between wanting to learn C++ and the speed requirements of my project, I've gone with C++.

Would it be a better idea to change the container from a template to a container for an abstract class that can implement its own destructor?

like image 996
alexgolec Avatar asked Feb 03 '10 20:02

alexgolec


People also ask

When to use delete [] or delete?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.

Can we use delete in destructor?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

In which case will using a delete this in destructor goes wrong?

No you should not delete this from the destructor. The destructor gets called because of a delete statement (or goes out of scope) and this would most likely lead to some sort of crash.

What is difference between delete and delete [] in C ++?

What is the difference between delete and delete[ ] in C++? Explanation : delete is used to delete a single object initiated using new keyword whereas delete[ ] is used to delete a group of objects initiated with the new operator.


1 Answers

If you don't know whether it was allocated with new or new[], then it is not safe to delete it.

Your code may appear to work. For example, on one platform I work on, the difference only matters when you have an array of objects that have destructors. So, you do this:

// by luck, this works on my preferred platform
// don't do this - just an example of why your code seems to work
int *ints = new int[20];
delete ints;

but then you do this:

// crashes on my platform
std::string *strings = new std::string[10];
delete strings;
like image 167
R Samuel Klatchko Avatar answered Sep 21 '22 14:09

R Samuel Klatchko