Monday, March 8, 2010

Learning Cpp -- When to use 'new' -- Stack or Heap


Use new to define large large chunks of dataMore typically, you use new with larger chunks of data, such as arrays, strings, and structures. This is where new is useful. Suppose, for ample, you’re writing a program that might or might not need an array, ending on information given to the program while it is running. If you create an array by declaring it, the space is allocated when the program is compiled. Whether or not the program finally uses the array, the array is there, using up memory. Allocating the array during compile time is called static binding, meaning that the array is built in to the program at compile time. But with new, you can create an array during runtime if you need it and skip creating the array if you don’t need it.Or you can select an array size after the program is running. This is called dynamic binding, meaning that the array is created while the program is running. Such an array is called a dynamic array. With static binding, you must specify the array size when you write the program. With dynamic binding, the program can decide on an array size while the program runs.

0 comments:

Post a Comment