如果一個物件是在 C++ 中的程式碼塊內建立的,它會被儲存在哪裡?


在本節中,我們將討論當 C++ 程式編譯時,變數和物件在記憶體中儲存的位置。眾所周知,記憶體中有兩個部分可以儲存物件:

  • − 所有在記憶體塊內宣告的成員都儲存在棧段中。主函式也是一個函式,因此其中的元素將儲存在棧中。

  • − 當一些物件被動態分配時,它們將儲存在堆段中。

在程式碼塊或函式內宣告的物件的作用域僅限於其建立所在的程式碼塊。當物件在程式碼塊內建立時,它將儲存在棧中,當控制流退出程式碼塊或函式時,物件將被移除或銷燬。

對於動態分配的物件(在執行時),物件將儲存在堆上。這是藉助 new 運算子完成的。要銷燬該物件,我們必須使用 del 關鍵字顯式地銷燬它。

示例

讓我們看看下面的實現,以便更好地理解:

 線上演示

#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 will be stored in the stack
      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;{
      //Object will be placed in the heap section, and local
      pointer variable will be stored inside stack
      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

更新於: 2020-08-27

1K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.