When a variable passes out of scope is the memory freed up in the same way that the dynamic memory would be with delete |
This is true. Sorta. See info about the stack at the end of this post.
I have also read that when a dynamically allocated variable passes from scope its memory is released without having to use the keyword delete |
This is false. One of the entire reasons you'd want to use dynamic memory is the ability to control it's lifetime. It does
not automatically delete itself. You must do it or it stays allocated forever (or really until the program ends).
Other languages (C#, Java), have a garbage collector which gets rid of dynamically allocated memory that is no longer in use, but
C and C++ do not.
would it not be more efficient to use dynamic memory, use a pointer, and then free the memory up with delete immediately when and after I need the memory location? |
No that would not be more efficient because memory allocation is a more complex task than that.
How it works with locally allocated variables is there's a stack. Your program has a bunch of stack space allocated for it when it starts up. And whenever you enter a function, all the local vars that function uses go on the stack.
So as you get deeper and deeper in function calls, you use more and more of the stack. But as you exit those functions, you get that stack space back.
Note that all this memory is allocated up-front. So putting it on/off the stack doesn't really allocate new space, it just uses the space that's already there.
Therefore, as long as you don't exceed your stack space (which is actually hard to do unless you put really, really large objects/arrays on the stack) -- then putting things on the stack is harmless.