Creating an object: with or without `new`
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocates an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword
delete
;Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.