~
संकेत करता है कि यह एक विनाशक है और जब कभी वस्तु गुंजाइश से बाहर हो जाती है, तो इसी विनाशक को बुलाया जाता है।
जब विनाशक कहा जाता है?
एक उदाहरण ले रहा है -
#include <iostream>
class foo
{
public:
void checkDestructorCall() ;
~foo();
};
void foo::checkDestructorCall()
{
foo objOne; // objOne goes out of scope because of being a locally created object upon return of checkDestructorCall
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
}
int main()
{
foo obj; // obj goes of scope upon return of main
obj.checkDestructorCall();
return 0;
}
अपने सिस्टम पर परिणाम:
Destructor called 0xbfec7942
Destructor called 0xbfec7943
यह उदाहरण केवल जब एक नाशक कहा जाता है इंगित करने के लिए कार्य करता है। लेकिन विनाशक केवल तभी लिखा जाता है जब वर्ग संसाधनों का प्रबंधन करता है।
जब कक्षा संसाधनों का प्रबंधन करती है?
#include <iostream>
class foo
{
int *ptr;
public:
foo() ; // Constructor
~foo() ;
};
foo:: foo()
{
ptr = new int ; // ptr is managing resources.
// This assignment can be modified to take place in initializer lists too.
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
delete ptr ; // Returning back the resources acquired from the free store.
// If this isn't done, program gives memory leaks.
}
int main()
{
foo *obj = new foo;
// obj is pointing to resources acquired from free store. Or the object it is pointing to lies on heap. So, we need to explicitly call delete on the pointer object.
delete obj ; // Calls the ~foo
return 0;
}
अपने सिस्टम पर परिणाम:
Destructor called 0x9b68008
और कार्यक्रम में आपने पोस्ट मैं नाशक लिखने के लिए एक की जरूरत नहीं दिख रहा। आशा करता हूँ की ये काम करेगा !
या जब विलोपन हो जाती हैं। – justkt
ध्यान दें कि '~' एक अलग संदर्भ में बिटवाई को भी इंगित नहीं कर सकता है। – Muggen
+1 लेकिन "हटाएं" शब्द पर सटीकता जोड़ा गया। – Klaim