When should I use "new"?

Possible Duplicate:
When should I use the new keyword in C++?

I don't know the difference between case 1 and case 2:

I define a struct below:

struct Graph {
    int ID;
}

Case 1:

Graph g;
g.ID = 1;

case 2:

Graph* g = new G();
g.ID = 1;

Are these two cases the same? What's the difference?


In case 1, the memory used by g is allocated on the stack, which means that it will be automatically freed when the function it is in returns.

In case 2, the memory used by g is allocated on the heap, which means that it will only be freed when explicitly deleted using the delete operator.

Also, in case 2 since g is a pointer, you should be accessing fields of g using the -> operator:

g->ID = 1;

In case 2 you mean new Graph and then g->ID = 1 . Try starting from http://en.wikipedia.org/wiki/New_(C%2B%2B) . Short story, case 1 allocates memory at compile time, while case 2 allocates it at run time.


The difference is where the data is allocated.

In Case 1, the data for your Graph struct is allocated on the stack. You access it via the name "g".

In Case 2, the data for your Graph struct is allocated on the heap. You access it via a pointer to that data, which is held via the name "g".

链接地址: http://www.djcxy.com/p/96530.html

上一篇: 将数据成员存储在堆内存上

下一篇: 我应该何时使用“新”?