[英]Heap and Stack memory storage in C++
我对以下简单程序的某些成员将在何处存储感到有些困惑?
#include <iostream>
using namespace std;
class Human
{
public:
int *age; //where will it get storage?
string *name; //where will it get storage?
Human(string name, int age)
{
this->name = new string; //string will got into heap
this->age = new int; //int will go into heap
*(this->name) = name;
*(this->age) = age;
}
void display()
{
cout << "Name : " << *name << " Age : " << *age << endl;
}
~Human()
{
cout << "Freeing memory";
delete(name);
delete(age);
}
};
int main()
{
Human *human = new Human("naveen", 24); //human object will go into heap
human->display();
delete(human);
return 0;
}
我已经使用new
运算符创建了一个Human
类。 因此,它肯定会在堆中获得存储。 但是,其属性的age
和name
将从何处获得存储空间?
成员变量age
和name
分别是指向int
和string
指针,将根据创建Human
类对象的方式存储在堆或堆栈中。
存储在堆栈上:
Human human("naveen", 24); // human object is stored on the stack and thus it's pointer members `age` and `name` are stored on the stack too
存储在堆上:
Human *human = new Human("naveen", 24); // human object is stored on the heap and thus it's pointer members `age` and `name` are stored on the heap too
您提供的代码:
Human *human = new Human("naveen", 24); //human object will go into heap
//human object will go into heap
仅仅是意味着Human
类的所有成员都存储在堆中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.