如果一个对象是在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP