3

I have in my c++ class member:

char array[24];

What to do with this member in the destructor or may be nothing ? Thanks for advice.

crocus
  • 81
  • 1
  • 6

2 Answers2

5

Nothing. You don't allocate space for array manually, so you shouldn't free it manually.

ForEveR
  • 53,801
  • 2
  • 106
  • 128
  • 2
    Kind of, but not exactly. The correct answer is nothing, but the array is not necessarily on the stack. It's wherever the object was allocated. So if `c` is allocated by `new`, then the memory for `array` is in the heap, but will automatically be cleaned up as part of `delete c;` – Anthony Mar 21 '13 at 05:46
  • @anthony-arnold thanks. fixed. – ForEveR Mar 21 '13 at 05:52
1

Allocation/deallocation applies for objects constructed on free-store (using malloc/new etc.) the array in the class will have its lifetime same as the object of the class. So you should be concerned about handling the allocation/deallocation of objects and not their members (when members are not pointers).

When a member variable is a pointer and it points to dynamically allocated memory/object then you need to deallocate it (preferably in the destructor).

For example:

class A { };

class B {

    A* a;

    B() { 
        a = new A;
    }

    ~B() { 
        delete a; 
    }
};
Anthony
  • 11,737
  • 9
  • 66
  • 101
A. K.
  • 30,148
  • 15
  • 48
  • 80