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

Recommended Answers

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.

Jump to Post

All 2 Replies

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];
               memcpy(deep[i],b.deep[i],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.

commented: Please don't answer class problem questions like this! -3

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.