在本节中,我们将讨论在编译C ++程序时变量和对象在内存中的存储位置。众所周知,有两个部分可以存储对象-
堆栈-在内存块中声明的所有成员,都存储在堆栈部分中。main函数也是一个函数,因此其中的元素将存储在堆栈中。
堆-当动态分配一些对象时,则将其存储在堆部分中。
在块或函数内部声明的对象范围仅限于在其中创建对象的块。当在块内创建对象时,该对象将存储在堆栈中;当控件退出该块或函数时,该对象将被删除或销毁。
对于动态分配的对象(在运行时),该对象将存储在堆中。这是在新运算符的帮助下完成的。要销毁该对象,我们必须使用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 << "盒子尺寸为:" << 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;{
//对象将放置在堆部分中,并在本地
pointer variable will be stored inside stack
Box* box_ptr1 = new Box(5, 6);
box_ptr = box_ptr1;
cout << "---------------------------------------------------" << endl;
cout << "方框2的尺寸为:" << 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 << "box2的宽度:" << box_ptr->get_width() << endl;
}输出结果
盒子尺寸为: Length : 2 Width :3 Box is destroying Exitting block, destructor Automatically call for the object stored in stack. --------------------------------------------------- 方框2的尺寸为: length : 5 width :6 Box is destroying length of box2 : 0 box2的宽度:0