C ++中的内存分配

时间:2011-01-10 03:19:15

标签: c++

我对C ++中的内存分配感到困惑。任何人都可以指导我分配下面代码段中的每个变量的位置。如何确定在堆栈上分配的内容以及在堆上分配的内容。有没有很好的网络参考来学习这个。

   class Sample {
    private:
        int *p;
    public: 
        Sample() {
            p = new int;
        }
    };

    int* function(void) {
        int *p;
        p = new int;
        *p = 1;

        Sample s;

        return p;
    }

4 个答案:

答案 0 :(得分:1)

如果它是通过new创建的,它就在堆中。如果它在一个函数内部,并且它不是static,那么它就在堆栈中。否则,它在全局(非堆栈)内存中。

class Sample {
    private:
        int *p;
    public: 
        Sample() {
            p = new int;  // p points to memory that's in the heap
        }

       // Any memory allocated in the constructor should be deleted in the destructor; 
       // so I've added a destructor for you:
        ~Sample() { delete p;}

        // And in fact, your constructor would be safer if written like this:
        // Sample() : p(new int) {}
        // because then there'd be no risk of p being uninitialized when
        // the destructor runs.
        //
        // (You should also learn about the use of shared_ptr,
        //  which is just a little beyond what you've asked about here.)
    };

    int* function(void) {
        static int stat; // stat is in global memory (though not in global scope)
        int *p;          // The pointer itself, p, is on the stack...
        p = new int;     // ... but it now points to memory that's in the heap
        *p = 1;

        Sample s;        // s is allocated on the stack

        return p;
    }

}

int foo; // In global memory, and available to other compilation units via extern

int main(int argc, char *argv[]) { 
// Your program here...

答案 1 :(得分:1)

哪里有new个关键字,它会在堆上分配。

class Sample {
private:
    int *p; //allocated on stack
public: 
    Sample() {
        p = new int; //integer gets allocated on heap
    }
};

int* function(void) {
    int *p;        //allocated on stack
    p = new int;   //integer gets allocated on heap
    *p = 1;

    Sample s;      //allocated on stack

    return p;
}

答案 2 :(得分:0)

new的所有内容都在堆上。 s的{​​{1}}在堆栈上分配内存。

答案 3 :(得分:0)

class Sample {
private:
    int *p; 
public: 
    Sample() {
        p = new int; //<--allocated on the heap. Anything created with operator new is allocated on the heap.
    }
};

int* function(void) {
    int *p; //<-- pointer is allocated on the stack as it is a local variable
    p = new int; //<-- the value pointed to by p is allocated on the heap (new operator)
    *p = 1;

    Sample s; //<--Allocated on the stack (local variable).

    return p;
}