简体   繁体   English

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

[英]Heap and Stack memory storage in C++

I am a little bit confused about where certain members of my following simple program will get storage? 我对以下简单程序的某些成员将在何处存储感到有些困惑?

#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;
}

I have created a class Human object using new operator. 我已经使用new运算符创建了一个Human类。 Hence, it will definitely get storage in heap. 因此,它肯定会在堆中获得存储。 But where will its properties age and name will get the storage? 但是,其属性的agename将从何处获得存储空间?

The member variables age and name which are pointers to int and string respectively will be stored on the heap or the stack depending on how you create an object of the Human class. 成员变量agename分别是指向intstring指针,将根据创建Human类对象的方式存储在堆或堆栈中。

Stored on the stack: 存储在堆栈上:

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

Stored on the heap: 存储在堆上:

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

The code you provided : 您提供的代码:

Human *human = new Human("naveen", 24); //human object will go into heap

//human object will go into heap merely means that all members of the Human class are stored on the heap. //human object will go into heap仅仅是意味着Human类的所有成员都存储在堆中。

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

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