im having a little trouble understanding when and why to dynamically allocate memory using new. it seems easier just declaring a variable and letting it go out of scope eventually. examples would help.
Local variables are placed on the stack. Stack space is limited in comparison to Heap memory space in Win32. Of course you can adjust your stack space but in general when you need large quantities of memory you are better off using heap memory for it.
Of course another obvious reason is when local variables that go out of scope just will not meet your requirements.
Keep in mind that when a class object is allocated on the heap all of it’s data member variables are included in that allocation. As an example if you have a CView derived class instance in a MFC SDI application that has a CFont member variable the CFont is on the heap since the MFC framework allocates the CView on the heap as part of it’s dynamic creation code. Conversely, in a MFC App Wizard Dialog based application the dialog instance is placed on the stack and so therefore all it’s member variables.
Now that is just a high level, general rule of thumb. If you want something more specific and detailed perhaps someone else will jump in here?
new is also handy when you MUST create an object/ group of objects at runtime. For instance, arrays created at compile time must be of static size. If you want to dynamically create one, you need new.
Let's say you need to create an int array of someNum size, and you won't know someNum's value until the user passes it. You can use new to create the array of the proper size by making the declaration:
There are a few situations where it is necessary to use new.
For e.g.,
suppose we create a linked list with the following node structure.
struct node{
int data;
node* next;
};
If you are create the linked list in one function(where you will assign value to next) and use the linked list in another function, you can't assign the address of a local variable to next when you create the linked list(because that address will become invalid after the local variable goes out of scope) as it is inaccessible from the other function.
Point taken, PerFnurt, but I feel it's important to know how the data structures you mention work, and because these data structures are built for generic flexibility, custom-built structures can offer increased efficiency.
Also, what would happen if you wanted a circular linked-list, or some structure not found in the STL? Not knowing how to dynamically allocate memory may present problems for the coder in their future.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.