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
  • 91
  • 2
  • 7

2 Answers2

5

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

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • 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
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
  • 12,177
  • 9
  • 69
  • 105
A. K.
  • 34,395
  • 15
  • 52
  • 89