在应用程序中,资源是应用程序使用的任何虚拟组件,例如纹理和声音。我们可以用析构函数清理资源吗?如果可以,请提供一个演示示例。谢谢。
我尝试使用析构函数进行清理,但值仍然存在。为什么调用析构函数后对象没有被删除?
#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;
}