Looked at the lecture here. Describes how to create a class for an array. In particular, we are talking about redefining the assignment operator and its work for the case a = a; (Timing 1: 2: 40).

Array& Array::operator=(MyArray &a){ mySize = a.mySize; delete [] myData; myData = new int[mySize]; for(int i=0;i<mySize;i++){ myData[i] = a.myData[i]; } return *this; } 

Well, somewhere goes:

 Array a(10); a.set(0,1000);//a[0]==1000; a=a; //a[0]==? 

And it is declared that in this case, after freeing memory through delete, the old pointer may already contain garbage and will continue to copy this garbage.

Question: where will a.myData refer a.myData after myData = new int[mySize] ?

I have a feeling that the new area, not the old one, and garbage (in the form of zeros, for example) will always be there, and not so that after deletion, "another part of our program can start using this area" and therefore there will be garbage which we copy later.

    1 answer 1

    • This code for calling a = a equivalent to the following code:

        mySize = this->ySize; delete [] myData; myData = new int[mySize]; for(int i=0;i<mySize;i++){ myData[i] = this->myData[i]; } 
    • In this case, there are no memory leaks and there are no dangling pointers, however, there is an undefined behavior in the line where the data is copied (reading data from the newly allocated block of memory is the undefined behavior ).

    • Answering specifically your question - a.myData and myData in operator= equivalent when they call a=a , that is, they always refer to the same memory location.

    • And how to get around the problem? Compare this and if they are the same, then immediately on the way out? - gecube
    • one
      @gecube Usually, yes. - AlexeyM
    • @AlexeyM, and what other options? - gecube
    • @ Kotik_hokhet_kusat, well, that is, the lecturer slightly confused students. Students swallowed. Thanks for the answer. @gecube, there is still a non-optimal option to pass a parameter not by reference, but by value, then a copy will be created a, taking into account that the copy constructor is described. - Yura Ivanov