chris skrev:
> Hi all,
>
> I need to know, what is the difference between dynamic memory
> allocation, and stack allocation ?
> 1. If I have a class named DestinationAddress, when should I use
> dynamic memory allocation to create object of that class ?
Dynamic allocation allows you to create an object and return it. It
also allows you to not have any object at all. Finally, dynamic
allocation allows you to determine the type of the object at run-time.
If you need to use any of these features, you should use dynamic
allocation.
Stack allocation is faster and ensures automatic destruction when you
leave scope. You should normally prefer this if you can. An exception
could be if you use huge C-style arrays or otherwise have an object
that requires vast amounts of storage, but that would be an extreme
case in a normal system.
> 2. If it says "dynamic memory allocation", is it mean the
> following code :
> DestinationAddress* dest = new DestinationAddress(); // code 1
>
> doesn't allocate address when compile time, but in run time ?
Correct.
>
> So, the following code :
> DestinationAddress dest; // code 2
>
> does allocate memory when compile time ?
Well, not actually. But the "allocation" is made for all local object
at entry to the function and the prize for this allocation is so low
that you can ignore the cost (at least on all architectures I'm aware
of).
>
> 3. In Java programming language, all object created on heap,
> just like dynamic memory allocation on C++. So, why should
> I use non-dynamic memory allocation just like on code 2 ?
Because you care about perfomance and ease of programming. Java is an
entirely different language where a garbage collecter takes care of
releasing your memory. In C++ there is (by default) no garbage
collection so you're on your own. In return C++ gives you deterministic
destruction on all objects and this is in my opinion far more valuable
(it is also one reason why C++ does not need finally).
>
> Thanks in advance
/Peter
|