为什么返回数据结构而不是指针弄乱了我的数据的完整性



我正在构建一个稀疏的矩阵类,该类容量有两个阵列(行和列),以双重链接的列表(向下和右)。有点这样:

 rows
c0123456789
o1
l2
u3
m4  A-->B-->
n5  |   |
s6  |   V
 7  V   D-->
 8  C-->
 9  

两个阵列都初始化为在每个空间中具有nullptr,直到在该位置插入某些东西为止。

我具有一个函数" readfile",该函数可以从文本文件中读取对象,并将它们插入此稀疏矩阵中。由于某种原因,在此功能返回之前,其中所有数据都很好,但是返回后,我的数组中会得到随机的内存位置。这是main.cpp

#include <iostream>
#include <string>
#include <fstream>
#include "sparseMatrix.h"
using namespace std;
class basic 
{
private:
    int x, y;
    string word;
    basic *down;
    basic *right;
public:
    basic(int x, int y, string word)
    {
        this->x = x;
        this->y = y;
        this->word = word;
        down = nullptr;
        right = nullptr;
    }
    int getX()
    {
        return x;
    }
    int getY()
    {
        return y;
    }
    basic *getRight()
    {
        return right;
    }
    void setRight(basic *newRight)
    {
        right = newRight;
    }
    basic *getDown()
    {
        return down;
    }
    void setDown(basic *newDown)
    {
        down = newDown;
    }
    void print()
    {
        cout << "X: " << x << ", Y: " << y << ", word: " << word << ".n";
    }
};
sparseMatrix<basic> readFileBROKEN(string pathToFile);
sparseMatrix<basic> *readFile(string pathToFile);
int main()
{
    cout << "Working:nn";
    sparseMatrix<basic> *workingMatrix = readFile("C:/users/jmhjr/desktop/testdata.txt");
    cout << "After returning, here are all the locations that are NOT nullptr:n";
    workingMatrix->printyArray();
    cin.get();
    cout << "Not working:nn";
    sparseMatrix<basic> brokenMatrix = readFileBROKEN("C:/users/jmhjr/desktop/testdata.txt");
    cout << "After returning, here are all the locations that are NOT nullptr:n";
    brokenMatrix.printyArray();
    cin.get();
    delete workingMatrix;
}
sparseMatrix<basic> readFileBROKEN(string pathToFile)
{
    ifstream inputFile;
    inputFile.open(pathToFile);
    if (inputFile.fail())
    {
        cout << "Couldn't open " << pathToFile << "!n";
        exit(-1);
    }
    sparseMatrix<basic> matrix(100, 100);
    while (!inputFile.eof())
    {
        int x, y;
        string word;
        inputFile >> x >> y >> word;
        basic data(x, y, word);
        matrix.insert(data);
    }
    cout << "Before returning, here are all the locations that are NOT nullptr:n";
    matrix.printyArray();
    cout << "press ENTER to returnn";
    cin.get();
    return matrix;
}
sparseMatrix<basic> *readFile(string pathToFile)
{
    ifstream inputFile;
    inputFile.open(pathToFile);
    if (inputFile.fail())
    {
        cout << "Couldn't open " << pathToFile << "!n";
        exit(-1);
    }
    sparseMatrix<basic> *matrix = new sparseMatrix<basic>(100, 100);
    while (!inputFile.eof())
    {
        int x, y;
        string word;
        inputFile >> x >> y >> word;
        basic data(x, y, word);
        matrix->insert(data);
    }
    cout << "Before returning, here are all the locations that are NOT nullptr:n";
    matrix->printyArray();
    cout << "press ENTER to returnn";
    cin.get();
    return matrix;
}

这是sparsematrix.h:

template <class dataType>
class sparseMatrix
{
private:
        //The dimensions of the sparse matrix.
    int width;
    int height;
        //Dynamic array of pointers to heads of linked lists.
    dataType** xArray;
    dataType** yArray;
public:
        //Constructor. Sets everything in the two arrays to nullptr.
    sparseMatrix(int height, int width)
    {
        this->width = width;
        this->height = height;
        xArray = new dataType*[width];
        yArray = new dataType*[height];
        for (int row = 0; row < height; row++)
        {
            this->yArray[row] = nullptr;
        }
        for (int col = 0; col < width; col++)
        {
            this->xArray[col] = nullptr;
        }
    }
        //Deconstructor. First goes through the matrix and looks for every city it can find, and deletes
        //all of those. Then when it's done, it deletes the two dynamic arrays.
    ~sparseMatrix()
    {
        dataType *currentdataType;
        dataType *next;
        for (int row = 0; row < height; row++)
        {
            currentdataType = yArray[row];
            while (currentdataType != nullptr)
            {
                next = currentdataType->getRight();
                delete currentdataType;
                currentdataType = next;
            }
        }
        delete [] yArray;
        delete [] xArray;
    }

        //Creates a copy of the data we are passed, then creates links to this copy.
    void insert(dataType data)
    {
            //Make sure the data is valid.
        if (data.getX() < 0 || data.getX() >= width || data.getY() < 0 || data.getY() >= height)
        {
            std::cout << "That dataType doesn't fit into the sparse matrix!n";
            data.print();
            std::cin.get();
        }
        else
        {
                //Copy the data we were passed.
            dataType *newData = new dataType(data);
                //Easy case. If nothing is in this row, set yArray[row] to the address of this data.
            if (yArray[data.getY()] == nullptr)
            {
                yArray[data.getY()] = newData;
            }
                //Not so easy case. Move forward (right) until we find the right location, then set links.
            else
            {
                dataType *current = yArray[data.getY()];
                while (current->getRight() != nullptr)
                {
                    current = current->getRight();
                }
                current->setRight(newData);
            }
                //Easy case. If nothing is in this col, set xArray[col] to the address of this data.
            if (xArray[data.getX()] == nullptr)
            {
                xArray[data.getX()] = newData;
            }
                //Not so easy case. Move forward (down) until we find the right location, then set links.
            else
            {
                dataType *current = xArray[data.getX()];
                while (current->getDown() != nullptr)
                {
                    current = current->getDown();
                }
                current->setDown(newData);
            }
        }
    }
    void printyArray()
    {
        for (int r = 0; r < height; r++)
        {
            if (yArray[r] != nullptr)
            {
                std::cout << r << ' ';
                //yArray[r]->print();
            }
        }
    }
};

ReadFile从看起来像这样的文件中读取所有内容:

0   0   hello
5   2   world
6   8   foo
9   5   bar
...

正如预期的那样,在返回之前,唯一不是nullptr的位置是我插入的位置。(0、2、8和5)。但是,当函数返回时,数组中的每个位置均不是nullptr。我添加了第二个功能,该功能将指针返回到动态分配的Sparsematrix对象,而不是返回对象本身,然后将其修复。但是,我不明白为什么。看来这两个功能的行为应以相同的方式。

另外,最让我混淆的部分,为什么在Xcode中运行得很好,而在Visual Studio中却不是?

tomse的答案是正确的,并给出了原因和修复程序,但对于此问题来说,这是一个不必要的昂贵解决方案。他对复制构造函数的建议还解决了许多未来的问题,例如Classics 为什么我的矢量会吃我的数据? dude,我的segfault在哪里?使复制构造函数。除非必须。

,不要使用它。

我认为Andras Fekete解决了问题,但他的职位有点乱七八糟。不过,他的解决方案正在爆炸。

这样定义您的功能:

bool readFile(string pathToFile, sparseMatrix<basic> & matrix)

删除函数内部矩阵的定义,有利于传递的矩阵。

返回错误时错误,因此您知道矩阵不好(或使用异常)。

在调用函数中创建矩阵并将其传递到修订的读取器函数中。

sparseMatrix<basic> matrix(100, 100);
if readFile("C:/users/jmhjr/desktop/testdata.txt", matrix);

将您放回指针版本的位置,但没有指针,而无需进行额外的工作来复制您不需要复制的数据。

您的功能:

sparseMatrix<basic> readFileBROKEN(string pathToFile)

返回对象的副本(可以的),但是sparseMatrix并未定义复制构造函数,因此将使用默认生成的构造函数,该默认生成的副本可以通过仅复制返回对象中的adresses来创建浅副本。但是,当您离开函数时,地址指向的内存将被删除(因为称为本地创建的对象的破坏者)。

要解决此问题,您必须在sparseMatrix中定义您自己的复制创建器,该文件复制对象的所有内容。

sparseMatrix(const sparseMatrix& rhs) :
  width(rhs.width),
  height(rhs.height),
  xArray(nullptr),
  yArray(nullptr)
{
  ... and now copy all the content from rhs.xArray to this->xArray,
  (same for yArray)
}

问题是您在两个读取文件函数中分配'矩阵'。从函数返回后,两个变量均被划分。但是,返回值(ERADFILE)矩阵已复制到您的调用功能的变量中,而返回指针(readFileBroken)只是返回曾经存储的矩阵的地址。

>

要解决此问题,您应该分配"矩阵"变量,然后对函数进行引用。然后,该功能可以在正确填充矩阵时返回空隙。

最新更新