Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

level10boy

Calling destructors in C++ explicitly

This topic is 6197 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
you can easy call the Desctructor like an other function (e.g. ~Test(); ). This would destroy the current object.

Peter Gmeiner

Share this post


Link to post
Share on other sites
Hmmm...
  
#include <iostream>

using namespace std;

class Test
{
public:
void foo () { this->~Test (); }
~Test () { cout << "I''m dying!\n"; }
};

int main ()
{
Test t;
t.foo ();
return 0;
}

Output:
I''m dying!
I''m dying!

steg, you are the weakest link. Goodbye.

Share this post


Link to post
Share on other sites
Note, the this-> is explicit because otherwise the compiler tries to interpret ~Test as the unary bit-inversion operator.

Share this post


Link to post
Share on other sites
There are very few times when you'd really want to call a destructor explicitly. So, if you notice yourself doing it more than once in a single project smaller than 5000 lines, re-think what you're doing.

Edited by - merlin9x9 on December 27, 2001 5:27:35 PM

Share this post


Link to post
Share on other sites
Ok Stoffel, but why would you want to call a destructor this way ?

Intrigued.

Reg''ds,
sTeVe

Share this post


Link to post
Share on other sites
Well, if your object was created by placement new, you need to call the destructor explicitly. I''m not entirely sure why you would do it from a member function, though ...

Share this post


Link to post
Share on other sites
The STL containers are a good example. The memory block is allready allocated, but you wan''t to create and destroy objects in this space- So when removing the object you don''t wan''t to free the memory region.

Share this post


Link to post
Share on other sites
If the object was created using the new operator, you would call delete to call the objects destructor, at least this way memory is cleaned up.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!