peter koch wrote:
chris skrev:
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).
Just to add to this for the OP, on those occasions where you need
dynamic storage duration, you are indeed on your own. By which I mean
that _you_ are responsible for paring every new with a delete and every
new[] with a delete[] to avoid leaking memory.
Wrap ALL you dynamic allocations in smart pointers (e.g. std::auto_ptr
or something from the boost smart pointers library) or other class
constructors and you will find this responsibility much less onerous.
Gavin Deane