2
|
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:
what's the difference between the following code snippets:
and
Why the former calls the destructor, but the latter doesn't (without explicit call to
destroy)?
Which one is preferred?
| ||
| add comment |
marked as duplicate by TheVillageIdiot, cobbal, Steve Fenton, Mehrdad Afshari, In silico Jun 14 '11 at 7:33
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
13
|
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:
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
deletes a char array that it did not new. In fact,nothing newd the C-style string; it came from a string literal. deleteing 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
deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken. | ||||||||||||||||||||||||||||||
|

"Hi there"– Loki Astari Jun 13 '11 at 22:53deleteinstead ofdestroy(which doesn't exist). – Christian RauJun 13 '11 at 23:19