Creating an object: with or without `new`

C++ConstructorNew OperatorDestructor

C++ Problem Overview


> 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?

C++ Solutions


Solution 1 - C++

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 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.

Solution 2 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionM.S. DoustiView Question on Stackoverflow
Solution 1 - C++Lightness Races in OrbitView Answer on Stackoverflow
Solution 2 - C++Jerry CoffinView Answer on Stackoverflow