Saturday, April 11, 2015

C++ Dynamic Storage


Local variables are allocated in stack.  The new operator allocate storage in heap.  Unlike stack, heap storage persist beyond the current scope.  On the other hands, heap storage must be freed via the delete operator.

int* p = new(int);  // new return a reference of the newly allocated storage
*p = 100;

When an object contains pointer to heap storage, the default destructor will lead to memory lead as the pointer will be released but not the area it points to.  Therefore, a customized destructor must be written and it should use delete to remove the dynamic area allocated.

A copy constructor has the same name of the class and accept a object of the same class.  For example,

Class C1 {
...

string p*

C1(const C1 &Ca) {
    p = new string(*(ca.p));
    }
...
}

The copy constructor is use to copy a object to another object of the same class.  The default copy constructor does a shallow copy.  In other words, if the class contains a pointer to a dynamically allocated area, the copy will be copy to the target object but the dynamic area will not be duplicated.  Both objects will point to the same area.  When one of the object is released, the destructor may release the dynamic area.  The remaining object will then end up containing a dangling pointer.

No comments: