1

I have a C++ class, MyClass. It contains a constructor, destructor and an int pointer private: int *MyPtr;.

Somewhere, I allocate dynamically a MyClass Object:

MyClass *my = new MyClass(); //...

Then I call delete my;

Should MyClass have a destructor which uses something like delete MyPtr? Or is that MyPtr destroyed when I call delete my?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
bit
  • 934
  • 1
  • 11
  • 32
  • `delete` what you `new`. Anyway, just use a smart pointer instead if you need DMA. – chris Jan 15 '13 at 07:04
  • Is `MyPtr` allocated in the constructor with `new`? If so then you need to manually call `delete` (and obey the **rule of three**). Otherwise no as your object does not own the pointer held by `MyPtr`. The call to delete should only be done by the owner of the pointer. You have not made clear the ownership semantics of your class so the answer is debatable. – Martin York Jan 15 '13 at 08:23

3 Answers3

5

If you allocated MyPtr insid MyClass constructor then it's your responsibility to delete it. Otherwise if you delete an unallocated memory it causes undefined behavior.

An idiomatic way is to use smart pointer inside class if you need to dynamic allocate memory and delete it, smart pointer will look after memory deallocation for you.

probaby worth a read: rule of three

Community
  • 1
  • 1
billz
  • 44,644
  • 9
  • 83
  • 100
3

Or is that MyPtr destroyed when I call delete my?

No, when you call delete my; this will call the destructor of MyClass and unless you explicitly delete MyPtr in the destructor you will have a memory leak.

Should MyClass have a destructor which uses something like delete MyPtr?

Always delete dynamically allocated memory in your destructor - that is what destructors are meant for.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • So, "delete my" instruction will deallocate the involved memory taken by my object instance, but not its fields such as MyPtr? Isn't it? – bit Jan 15 '13 at 07:15
  • 2
    Only the **pointer** MyPtr is a field in the class, not the memory it is pointing to. So when you destroy the class, the memory used for the pointer will be released, but not the memory **pointed to** by the pointer. Freeing that memory is your responsibility. – Ivaylo Strandjev Jan 15 '13 at 07:18
  • Assuming the object owns the pointer. That point is not made clear by the question. – Martin York Jan 15 '13 at 08:18
  • @LokiAstari true. I thought for a while if I should add this to my answer but thought it will be more confusing than helping. – Ivaylo Strandjev Jan 15 '13 at 08:20
  • @PeterWood I thought my first sentence made that clear. Do you think I should add it explicitly? – Ivaylo Strandjev Jan 15 '13 at 08:52
0

When you call

delete my

you don't deallocate the data of that class (unless you specify it in the destructor), so this will lead to a memory leak.

KamikazeCZ
  • 714
  • 8
  • 22