Question

In an application, a resource is any virtual components used by the application, such as texture and sound. Can we clean up a resource with destructor? If can, provide an demonstration example. Thanks.

I try to use destructor to do clean up but the value is still there. Why the object hasn't deleted after calling destructor?

#include <iostream>
using namespace std;

class Demo
{   
public:
Demo();       // Constructor prototype
~Demo();      // Destructor prototype

int a;
};

Demo::Demo()        // Constructor function definition
{   
cout << "An object has just been defined, so the constructor"
    << " is running.\n";
a = 1;
}

Demo::~Demo()       // Destructor function definition
{  
cout << "Now the destructor is running.\n";         
}

int main()
{   
cout << "This is displayed before the objects are created.\n";
Demo demoObjA, demoObjB;   // Define two Demo objects

cout << demoObjA.a << endl;
cout << "The objects now exist, but are about to be destroyed.\n";
demoObjA.~Demo();
cout << endl;

cout << demoObjA.a << endl;

cin.get();
return 0;   
}
Was it helpful?

Solution

Demo demoObjA;
demoObjA.~Demo();

You're doing it wrong.

demoObjA is an automatic variable. You do not manually destroy an automatic variable like this. Automatic variables will be automatically destroyed when they fall out of scope.

The code you have written to call the destructor is legal in C++, but highly unusual. You would never directly call a destructor unless you knew exactly what you were doing and why, and never for automatic variables (at least not any case I can think of). [Note: the only time you would normally directly call a destructor is on an object that has been instantiated using placement-new -- itself a highly unusual operation.]

Also,

demoObjA.~Demo();
cout << demoObjA.a << endl;

You seem to be asking why demoObjA.a still has a value of 1 (or any value at all) after you have called the destructor. The problem is, you have entered in to the land of Undefined Behavior. Once you call the destructor for demoObjA, the object is destroyed. You can't then access the members of demoObjA. If you do, it results in Undefined Behavior. Undefined Behavior means "anything can happen" and that includes reading a value that you previously stored in the object. It might look like your code is working, but it's not.

OTHER TIPS

You don't delete an object by calling the destructor directly. The destructor is called automatically when the object goes out of scope if declared statically (as they are now, as local variables) or if you delete them directly if they're dynamically-declared variables (using new).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top