繁体   English   中英

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

[英]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类。 因此,它肯定会在堆中获得存储。 但是,其属性的agename将从何处获得存储空间?

成员变量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类的所有成员都存储在堆中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM