इस खंड में हम चर्चा करेंगे कि जब C++ प्रोग्राम कंपाइल होता है तो वेरिएबल्स और ऑब्जेक्ट्स मेमोरी में कहां स्टोर होते हैं। जैसा कि हम जानते हैं, मेमोरी के दो भाग होते हैं जिनमें एक ऑब्जेक्ट स्टोर किया जा सकता है:
- स्टैक - मेमोरी के ब्लॉक के अंदर घोषित सभी सदस्य, स्टैक सेक्शन में स्टोर होते हैं। मुख्य फंक्शन भी एक फंक्शन है, इसलिए इसके अंदर के तत्व स्टैक में स्टोर होंगे।
- हीप - जब कुछ ऑब्जेक्ट्स डायनामिकली एलोकेटेड होते हैं, तो वे हीप सेक्शन में स्टोर होते हैं।
ब्लॉक या फंक्शन के अंदर घोषित ऑब्जेक्ट का स्कोप उस ब्लॉक तक सीमित होता है जिसमें यह बनाया गया है। ऑब्जेक्ट स्टैक में स्टोर होगा जब यह ब्लॉक के अंदर बनाया जाता है और जब कंट्रोल ब्लॉक या फंक्शन से बाहर निकलता है तो ऑब्जेक्ट हटा या नष्ट हो जाता है।
डायनामिकली एलोकेटेड ऑब्जेक्ट्स (रनटाइम के दौरान) के मामले में, ऑब्जेक्ट हीप पर स्टोर होगा। यह न्यू ऑपरेटर की मदद से किया जाता है। उस ऑब्जेक्ट को नष्ट करने के लिए, हमें डिलीट कीवर्ड का उपयोग करके इसे स्पष्ट रूप से नष्ट करना होगा।
उदाहरण
बेहतर समझ के लिए निम्न कार्यान्वयन देखें:
#include <iostream> using namespace std; class Box { int width; int length; public: Box(int length = 0, int width = 0) { this->length = length; this->width = width; } ~Box() { cout << "Box is destroying" << endl; } int get_len() { return length; } int get_width() { return width; } }; int main() { { Box b(2, 3); // b स्टैक में स्टोर होगा cout << "Box dimension is:" << endl; cout << "Length : " << b.get_len() << endl; cout << "Width :" << b.get_width() << endl; } cout << "\tExitting block, destructor" << endl; cout << "\tAutomatically call for the object stored in stack." << endl; Box* box_ptr;{ // ऑब्जेक्ट हीप सेक्शन में रखा जाएगा, और लोकल पॉइंटर वेरिएबल स्टैक में स्टोर होगा Box* box_ptr1 = new Box(5, 6); box_ptr = box_ptr1; cout << "---------------------------------------------------" << endl; cout << "Box 2 dimension is:" << endl; cout << "length : " << box_ptr1->get_len() << endl; cout << "width :" << box_ptr1->get_width() << endl; delete box_ptr1; } cout << "length of box2 : " << box_ptr->get_len() << endl; cout << "width of box2 :" << box_ptr->get_width() << endl; } आउटपुट
Box dimension is: Length : 2 Width :3 Box is destroying Exitting block, destructor Automatically call for the object stored in stack. --------------------------------------------------- Box 2 dimension is: length : 5 width :6 Box is destroying length of box2 : 0 width of box2 :0