C++在范围结束后丢失指针引用

标签 c++ pointers null-pointer

我遇到了一个非常奇怪的错误,在我离开 for 范围后,我无法访问我的指针在循环期间指向的任何内容,即使在类中声明了包含对象的数组标题。

这是代码的基础:

Class CTile{/*代码*/};

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

}

有谁知道哪里出了问题?

最佳答案

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

应该是

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

为什么?因为您复制了 CTile,而不是在二维数组中创建对 CTile 的引用。您现在可能会发现崩溃已转移到 me.setType(1) 语句。

关于C++在范围结束后丢失指针引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914196/

相关文章:

c++ - 如何在 Cilk Plus 中组织非线程安全资源池(每个工作人员一个资源)?

c++ - 为什么双端队列比队列快?

c++ - 将共享指针的派生类切换到基类

c - 取消引用空指针在 sizeof 操作中是否有效

c - 当我们将 "if(ptr==NULL)"用作整数指针 ptr 时,NULL 指针是否隐式转换为类型 (int*)?

c++ - 为什么标准容器使用函数模板而不是非模板 Koenig 运算符

.net - 不能在另一个项目的 dll 中使用一个类的 typedef

c - c中数组的地址分配和指向数组的指针

pointers - 当 Vec 被 move 时,我可以(不安全地)持有一个指向 Vec 元素的指针吗?

c++ - 为什么在C++中使用静态方法时对nullptr的取消引用不是未定义的行为?