Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
错误:在C++中释放一个2D数组_C++_Arrays_Visual C++ - Fatal编程技术网

错误:在C++中释放一个2D数组

错误:在C++中释放一个2D数组,c++,arrays,visual-c++,C++,Arrays,Visual C++,创建了一个MCVE 当我尝试取消分配ConnectNGame类中的2D数组时,出现了一个错误 下面是Source.cpp中的代码 #include <iostream> #include "ConnectNGame.h" using namespace std; int main() { int connect = 3; ConnectNGame game(connect); game.~ConnectNGame();

创建了一个MCVE

当我尝试取消分配ConnectNGame类中的2D数组时,出现了一个错误

下面是Source.cpp中的代码

#include <iostream>
#include "ConnectNGame.h"
using namespace std;

int main()
    {
        int connect = 3;
        ConnectNGame game(connect);
        game.~ConnectNGame();
        return 0;
    }
和ConnectNGame.cpp

#include <iostream>
#include "ConnectNGame.h"
using namespace std;

ConnectNGame::ConnectNGame()
{
    rows = 0;
    cols = 0;
}

ConnectNGame::ConnectNGame(int pieces)
{
    rows = pieces + 2;
    cols = pieces + 3;
    gameBoard = new char*[rows];
    for (int count = 0; count < rows; count++)
    {
        gameBoard[count] = new char[cols];
        for (int count2 = 0; count2 < cols; count2++){
            gameBoard[count][count2] = ' ';
        }
    }
}
ConnectNGame::~ConnectNGame()
{

    for (int i = 0; i < rows; i++) {
        delete[] gameBoard[i];
    }
    delete[] gameBoard;
}

调用析构函数时,程序崩溃。我不知道这是为什么,如果有任何帮助,我将不胜感激。

我的水晶球告诉我gameBoard实际上是一个不实践语义的类中的成员变量。贴一张。理想情况下,抛开它,只使用std::vector gameBoardrows,std::vectorcols@WhozCraig我编辑了OP,创建了一个关于我的错误的MCVE示例。关于三的规则,你可能是对的,因为我对它不太熟悉。该代码有多个问题,并且证实了我的水晶球仍然有一些牙齿。它不仅违反了我前面链接的三个语义规则,还使gameBoard在默认构造函数中不确定。由于行数为零,析构函数中的循环将被跳过,但您仍将传递一个指向最终delete[]的不确定指针,除非您初始化了对象的值,在这种情况下,gameBoard将为nullptr,delete[]将为no-op..,并且这仍然不是MCVE。没有代码实际上创建也不使用任何这些对象,也就是说,没有主函数,也没有任何函数,你可以通过连接引擎对象来传递,通过,等等,读一下我刚才说过的关于向量的向量。停止手动调用析构函数。删除此行:游戏。~ConnectNGame;。在范围退出时自动为您调用它。我仍然强调不够。你需要阅读这篇文章,看看轮子最终是如何脱离的,即使你没有手动调用析构函数,除非你在新的土地上玩,否则你永远不应该这样做,而你不是。
#include <iostream>
#include "ConnectNGame.h"
using namespace std;

ConnectNGame::ConnectNGame()
{
    rows = 0;
    cols = 0;
}

ConnectNGame::ConnectNGame(int pieces)
{
    rows = pieces + 2;
    cols = pieces + 3;
    gameBoard = new char*[rows];
    for (int count = 0; count < rows; count++)
    {
        gameBoard[count] = new char[cols];
        for (int count2 = 0; count2 < cols; count2++){
            gameBoard[count][count2] = ' ';
        }
    }
}
ConnectNGame::~ConnectNGame()
{

    for (int i = 0; i < rows; i++) {
        delete[] gameBoard[i];
    }
    delete[] gameBoard;
}