Possible Duplicate:
What is difference between instantiating an object using new vs. without
This is probably a basic question, and might have already been asked (say, here); yet I still don't understand it. So, let me ask it.
Consider the following C++ class:
class Obj{
char* str;
public:
Obj(char* s){
str = s;
cout << str;
}
~Obj(){
cout << "Done!\n";
delete str; // See the comment of "Loki Astari" below on why this line of code is bad practice
}
};
what's the difference between the following code snippets:
Obj o1 ("Hi\n");
and
Obj* o2 = new Obj("Hi\n");
Why the former calls the destructor, but the latter doesn't (without explicit call to delete
)?
Which one is preferred?
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.