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: