-3

I've searched for this but didn't find a similar topic.

If I have an object class, for example class Object { ... }; , and I have this pointer for it: Object* p = new Object();

I was wondering what is the correct way to delete this pointer, is it this:

delete (Object*) p;

Or this:

delete[] p;

I can't tell which one is the correct, I would be happy if someone could tell me what's right. Thank you <3

ConanCoder
  • 39
  • 2
  • 10

2 Answers2

1

If you are just allocate a single object using the new operator you should use delete to free that some object. If you are using the new[] operator (which is the array form) though to allocate multiple objects at once you should use delete[] to delete those accordingly.

See: http://www.cplusplus.com/reference/new/operator%20delete/ and http://www.cplusplus.com/reference/new/operator%20delete[]/

tuxtimo
  • 2,730
  • 20
  • 29
  • Thank you, same thing I asked him, what if I'm doing Object** p, an array of pointers of the type Object, do I pass on them one by one with loop and delete them or there is a different way ? – ConanCoder Jun 15 '19 at 14:42
0

is it this:

delete (Object*) p;

It is not. There is no need to cast an object of type Object* to the type Object*. That is redundant. Furthermore, C-style cast should be avoided.

Or this:

delete[] p;

It is not. delete[] must be used only with pointers returned from a new[] expression. You didn't use new[], so you may not use delete[]. You used new, so you must use delete.

The correct way is delete p;. However, you probably shouldn't have done Object* p = new Object(); in the first place. Instead use auto p = std::make_unique<Object>();. This way the allocation is deleted automatically and it will be much harder to write bugs. Also consider whether you need dynamic allocation in the first place. It should be avoided when it is not necessary.

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Thank you, though what if I'm doing this: Object** p, which means array of pointers to the type Object? do I still pass with a loop on each one and delete it the way you showed me ? – ConanCoder Jun 15 '19 at 14:41
  • @ConanCoder `Object** p` is not an array of pointers. It is a pointer to a pointer. – eerorika Jun 15 '19 at 14:42
  • Okay but I can look at it as if it's an array correct ? and still how do I free that ? – ConanCoder Jun 15 '19 at 14:44
  • 1
    @ConanCoder It doesn't matter how you look at it. What matters is how you have allocated. If you allocate with `new`, then use `delete`. If you have allocated with `new[]`, then use `delete[]`. – eerorika Jun 15 '19 at 14:45
  • Awesome, I think I got it, thanks for the help <3 – ConanCoder Jun 15 '19 at 14:46