C ++ Losing a pointer reference after scope completion

I get a really strange error when, after I leave the area for, I cannot access everything that my pointer pointed out during the loop, even if the array containing the objects is declared in the class header.

This is the main code:

Class CTile{ /*Code*/ };

Class CMap  
{  
    public:  
        CTile** tiles;  
        CMap();  
}

CMap::CMap()  
{  
    int lines = 10;
    int cols = 10;
    tiles = new CTile*[lines];  
    for(int i = 0 ; i (lower than) lines;++)  
    {  
        this->tiles[i] = new CTile[cols];  
    }  
    for(int curLine = 0; curLine (lower than) lines ; curLine++)  
        for(int curCol = 0; curCol (lower than) cols; curCol++)  
        {
            CTile me = this->tiles[curLine][curCol];
            me.setType(1);
            //do whatever I need, and inside the loop everything works.  
        }  
    int a = this->tiles[2][2].getType(); // a gets a really weird number 
    this->tiles[2][2].setType(10); // crashes the program

}

Does anyone know what could be wrong?

+3
source share
2 answers
CTile me = this->tiles[curLine][curCol];

It should be

CTile& me = this->tiles[curLine][curCol];
me.setType(1);

Why? Because you made a copy of CTile, instead of creating a reference to one in a two-dimensional array. Now you can find that the accident has moved to the operator me.setType(1).

+4
source
CTile  me = this->tiles[curLine][curCol];

. me - tiles[curLine][curCol], , me, . , me.setType(1). , .

, : :

CTile & me = this->tiles[curLine][curCol];
  //  ^ note this
me.setType(1);

, :

tiles[curLine][curCol].setType(1); //"this" is implicit!
+4

All Articles