Accumulator
Accumulator

Reputation: 903

Is deleting pointers in the destructor required?

If I do this:

class A {
    B* pointer01 = new B();
    C* pointer02 = new C();
}

do I have to do, in the destructor:

delete pointer01;
delete pointer02;

or not? I can't find anything on this.

Upvotes: 2

Views: 96

Answers (3)

luk32
luk32

Reputation: 16070

I think the other answers focus too much on what should one do, and good practices, while skipping the real answer altogether.

The answer is no. You are not required to do so. I don't think that there any place in the standard that says, one is required to have a delete for each new. (It would be nice to have a quotation, if that's not true, that would be a real answer too.)

However, certainly resource acquisition should be paired up with release. It's a very bad not do so. It is never a good idea, but doesn't make the program illegal.

I do agree with vsoftco's comment, that such a program is semantically incorrect, but I still think it would make a legal c++ code. (I don't know the standard by heart, and I couldn't find a place which states causing a memory leak or not pairing new with delete is illegal.)

Upvotes: 1

Baum mit Augen
Baum mit Augen

Reputation: 50043

If you actually are going to use pointers and dynamically allocated objects, then yes, you definitely should delete them in your destructor (unless you are doing something really weird and your class is not the owner of those objects. If that is the case, stop it). You will also most likely need appropriate copy and assignment semantics, see The Rule of Three.

However, it would most certainly be easier and better to just use automatic objects instead:

class A {
    B b;
    C c;
};

Upvotes: 3

Anedar
Anedar

Reputation: 4265

Yes, you have - basically every new needs a corresponding delete. But you can use smart-pointers (std::unique_ptr here) to make life easier.

Upvotes: 2

Related Questions