开发者

C++ Losing pointer reference after scope end

开发者 https://www.devze.com 2023-03-04 16:21 出处:网络
I\'m getting a really weird error where after I leave the for scope I can\'t access whatever my pointer was pointing during the loop even if the array holding the objects is declared in the class head

I'm getting a really weird error where after I leave the for scope I can't access whatever my pointer was pointing during the loop even if the array holding the objects is declared in the class header.

This is the basic of the 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];  
    }  
    fo开发者_StackOverflow中文版r(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?


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

That 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 the one in the 2-dimensional array. You might now discover that the crash has moved to the me.setType(1) statement.


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

Here is the problem. me is a copy of the original object tiles[curLine][curCol], so whatever you're doing with me isn't reflected in the original object. The orginal object remains unchanged even if you do me.setType(1). I'm sure you didn't want that.

So the fix is : use reference as :

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

Or better yet, you can simply do this:

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

精彩评论

暂无评论...
验证码 换一张
取 消