I don’t quite get the point of dynamically allocated memory and I am hoping you guys can make things clearer for me.
First of all, every time we allocate memory we simply get a pointer to that memory.
int * dynInt = new int;
So what is the difference between doing what I did above and:
int someInt;
int* dynInt = &someInt;
As I understand, in both cases memory is allocated for an int, and we get a pointer to that memory.
So what’s the difference between the two. When is one method preferred to the other.
Further more why do I need to free up memory with
delete dynInt;
in the first case, but not in the second case.
My guesses are:
-
When dynamically allocating memory for an object, the object doesn’t get initialized while if you do something like in the second case, the object get’s initialized. If this is the only difference, is there a any motivation behind this apart from the fact that dynamically allocating memory is faster.
-
The reason we don’t need to use delete for the second case is because the fact that the object was initialized creates some kind of an automatic destruction routine.
Those are just guesses would love it if someone corrected me and clarified things for me.
The difference is in storage duration.
Objects with automatic storage duration are your “normal” objects that automatically go out of scope at the end of the block in which they’re defined.
Create them like
int someInt;You may have heard of them as “stack objects”, though I object to this terminology.
Objects with dynamic storage duration have something of a “manual” lifetime; you have to destroy them yourself with
delete, and create them with the keywordnew.You may have heard of them as “heap objects”, though I object to this, too.
The use of pointers is actually not strictly relevant to either of them. You can have a pointer to an object of automatic storage duration (your second example), and you can have a pointer to an object of dynamic storage duration (your first example).
But it’s rare that you’ll want a pointer to an automatic object, because:
By contrast, dynamic objects are often accessed through pointers, simply because the syntax comes close to enforcing it.
newreturns a pointer for you to use, you have to pass a pointer todelete, and (aside from using references) there’s actually no other way to access the object. It lives “out there” in a cloud of dynamicness that’s not sitting in the local scope.Because of this, the usage of pointers is sometimes confused with the usage of dynamic storage, but in fact the former is not causally related to the latter.