How to delete an object (class) using the destructor method

I am interested to know if an object can be deleted using the destructor method?

The constructor and destructor of my class:

class cal { public: cal() { days = 0; day = 1; month = 1; year = 1300; leap = true; }; ~cal() { delete this; } }*calendar = new cal; 

How can I remove this pointer through a class?

PS

I forgot to write the following code

 cal *calandar = new cal[]; 

I want to use it on a heap not a stack

I want to often use this class (objects) (many of this object), imagine how long I have to write delete, and it makes a deep understanding, troubleshooting, and tracking codes. I want them to be automatically destroyed (on the heap)

I used the following code in my class, when I execute "delete [] calendar", it reduces the number of rams used (the number of bars used), does it work correctly (destroy all objects), leaving the program? Since I use GNU / Linus and it destroys all objects with or without these lines, I am worried about a leak in windows

 void DisposeObject() { delete this; } 
+7
source share
3 answers

You can write the code as follows:

 class cal { public: cal() { }; ~cal() { } void DisposeObject() { delete this; } } 

And he will call your destructor.

You should not call delete this from your destructor, as it will recursively call the destructor, which can lead to a stack overflow. Anyway, the code you wrote suffers from undefined behavior .

Refer to this question for an in-depth discussion: Is it allowed to delete?

+9
source

Not. By the time the destructor is called, the object is already destroyed, so delete this invalid.

The behavior is undefined, but most likely it will call the destructor recursively, resulting in a stack overflow.

+12
source

I am interested to know if an object can be deleted using the destructor method

Even assuming that this was true - the problem is that nothing will ever call the destructor, so it will never have an effect. The destructor is called when the calling code deletes the object, which in turn can delete any internal objects as necessary.

In your case, it doesn't seem like you need to do anything in the destructor, since you don't have resources that should be explicitly deleted (at least in what you show).

+3
source

All Articles