Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i call destructor from its class method?

Tags:

c++

destructor

I have a Thread class like bellow

class Thread {
public:
  Thread();
  ~Thread();
  void start();
  void stop();
}

So i need to call destructor from stop() method, is it a good way to do that?

like image 760
sayyed mohsen zahraee Avatar asked Nov 27 '13 07:11

sayyed mohsen zahraee


People also ask

How do you call a destructor from a class in C++?

Use the obj. ~ClassName() Notation to Explicitly Call a Destructor Function. Destructors are special functions that get executed when an object goes out of scope automatically or is deleted by an explicit call by the user.

What is the way to call destructor?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .

Can we call destructor without constructor?

Yes, the destructor is nothing more than a function. You can call it at any time. However, calling it without a matching constructor is a bad idea.

Can an object call its own destructor?

An explicit call to destructor is only necessary when an object is placed at a particular location in memory by using placement new. Destructor should not be called explicitly when the object is dynamically allocated because the delete operator automatically calls destructor. Example: CPP.


1 Answers

Technically yes, but be careful, you should not use the deleted object, this and non-static members anymore:

delete this;

You can also call the destructor:

~Thread();

However, in a well designed code, you can avoid these types of self destructions.

like image 190
masoud Avatar answered Oct 09 '22 05:10

masoud