how to do deep copy an array of pointers in a class (provide example) ?

Edited by happygeek: moved

5 Years
Discussion Span
Last Post by rubberman

In the copy constructor or method, copy all data or change all relevant pointers.

For example,

        struct Basic
           char ** deep;
           int num;

           Basic & operator=(const Basic & b)
             if( this == &b )   return *this;
             for(int i=0;i<num;++i) delete [] *(deep+i);
             delete [] deep;
             deep = new char * [b.num];
             for(int i=0;i<b.num;++i)
               deep[i] = new char[MAX_LEN];
             return *this;

You do this because in the best case of a shallow copy, the pointer to array 'deep' is copied directly. There are many worse cases.

Alternatively, you can pass possession of the pointer to the newer object. Only one object should "own" the base pointer, assuming you [wisely] deallocate the memory during deconstruction.
That would look something like this

struct Basic
  // ...
  Basic & operator=(const Basic & b)
    if( this == &b ) return *this;
    deep = b.deep;
    b.deep = NULL; // calling delete on a NULL ptr does nothing according to C standard.
    return *this;

However, this means that the original class object can no longer access the "deep" array of string.
How you approach the problem is up to you.

Edited by Unimportant

Votes + Comments
Please don't answer class problem questions like this!

We don't solve school work problems for you. Make an effort to solve them yourself, and we may decide to help you correct/fix them.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.