可以将对象存储在内存的两个部分中:
- 堆栈–堆栈中的内存供所有在块/功能内部声明的成员使用。注意main也是一个函数。
- 堆–该内存未使用,可用于在运行时动态分配内存。
在块或函数内部创建的对象的范围仅限于在其中创建对象的块。
- 在功能块内部创建的对象将存储在堆栈中,并且当函数/ block退出时,对象将被销毁并从堆栈中删除。
- 但是,如果我们在运行时即通过动态内存分配创建对象,则该对象将存储在堆中。这是在新运算符的帮助下完成的。在这种情况下,我们需要使用delete运算符显式销毁对象。
例子:
Output:
Inside Block1...
length of rectangle is : 2
width of rectangle is :3
Destructor of rectangle
with the exit of the block, destructor called
automatically for the object stored in stack.
*********************************************
Inside Block2
length of rectangle is : 5
width of rectangle is :6
Destructor of rectangle
length of rectangle is : 0
width of rectangle is :0
下面是显示对象存储位置的程序:
// C++ program for required implementation
#include
using namespace std;
class Rectangle {
int width;
int length;
public:
Rectangle()
{
length = 0;
width = 0;
}
Rectangle(int l, int w)
{
length = l;
width = w;
}
~Rectangle()
{
cout << "Destructor of rectangle" << endl;
}
int getLength()
{
return length;
}
int getWidth()
{
return width;
}
};
int main()
{
// Object creation inside block
{
Rectangle r(2, 3); // r is stored on stack
cout << "Inside Block1..." << endl;
cout << "length of rectangle is : "
<< r.getLength() << endl;
cout << "width of rectangle is :"
<< r.getWidth() << endl;
}
cout << " with the exit of the block, destructor\n"
<< " called automatically for the object stored in stack."
<< endl;
/*
// uncomment this code and run once you will get
// the compilation error because the object is not in scope
cout<<"length of rectangle is : "<< r.getLength();
cout<< "width of rectangle is :" << r.getWidth();
*/
Rectangle* ptr2;
{
// object will be stored in heap
// and pointer variable since its local
// to block will be stored in the stack
Rectangle* ptr3 = new Rectangle(5, 6);
ptr2 = ptr3;
cout << "********************************************"
<< endl;
cout << "Inside Block2" << endl;
cout << "length of rectangle is : "
<< ptr3->getLength() << endl;
cout << "width of rectangle is :"
<< ptr3->getWidth() << endl;
// comment below line of code and
// uncomment *important line*
// and then check the object will remain
// alive outside the block.
// explicitly destroy object stored on the heap
delete ptr3;
}
cout << "length of rectangle is : "
<< ptr2->getLength() << endl;
cout << "width of rectangle is :"
<< ptr2->getWidth() << endl;
// delete ptr2; /* important line*/
return 0;
}
输出:
Inside Block1...
length of rectangle is : 2
width of rectangle is :3
Destructor of rectangle
with the exit of the block, destructor
called automatically for the object stored in stack.
********************************************
Inside Block2
length of rectangle is : 5
width of rectangle is :6
Destructor of rectangle
length of rectangle is : 0
width of rectangle is :0
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。