Quote:Original post by rip-off
When dynamically creating a single instance of an object, one uses new. When dynamically creating an array, one uses new [].
However, everything you dynamically allocated, through either new or new [], must also be deallocated. Each allocate "function" has a corresponding deallocation "function": something allocated with new is deallocated
with
delete, and something allocated with
new [] is deallocated with
delete []. Hence I said new was paired with delete, and new[] paired with delete[] (typing all those bold tags is tiring [smile])
Those square brackets make a big difference! So, in your code, you use:
*** Source Snippet Removed ***
Followed by:
*** Source Snippet Removed ***
Can you see how that is wrong? Since you only allocated single instance, not an array (note: even if the array is only a single element long it is still different from a single instance) you must use delete to correctly deallocate the Sky object.
The next part of my post suggested alternatives. The alternative to new and delete is to use a smart object which will delete the object in its destructor. The Standard C++ Library smart pointer type std::auto_ptr would probably suffice in your example:
*** Source Snippet Removed ***
Of course, you could also allocate it on the stack (AKA: automatic allocation)
*** Source Snippet Removed ***
As I alluded too, the
Boost library ([boost]) contains a number of smart pointers to suit most situations (std::auto_ptr is rather misbehaved, its copy semantics are not for the inexperienced or faint of heart).
Thanks alot mate.
That was very well explained and you made it very easy to understand all the methods!
I will try them all out and see how it goes.
In your opinion which would you sujjest is the best method for using?
Generally earlier i had all my class objects like this:
CTerrain terrain;
then used it:
terrain.Draw();
but then I wanted to do it with pointers instead like u showed:
CTerrain *terrain = new CTerrain;
terrain->Draw();
delete terrain;
should I make all my code like this one (above), should I keep it like it is(first method aka. CTerrain terrain) or should I use smart pointer method you sujjested?
Which one would work/run the best/fastest? Or would it not really make much difference?
Thanks alot!