堆栈和堆栈内存存储在C ++中

时间:2015-10-11 18:16:00

标签: 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;
}

我使用Human运算符创建了一个类new对象。因此,它肯定会在堆中存储。但是它的属性agename将在哪里获得存储空间?

1 个答案:

答案 0 :(得分:4)

分别指向agename的成员变量intstring将存储在堆或堆栈上,具体取决于您创建对象的方式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类的所有成员都存储在堆上。