调用复制构造函数时,我的程序是seg faulting。这就是我的Grid类的构造函数:
Grid::Grid(unsigned int grid_size) {
size = grid_size;
grid = new char *[size];
for(int i = 0; i < size; i++) {
grid[i] = new char[size];
}
}
而且,这是导致问题的复制构造函数:
Grid::Grid(Grid const &other_grid) {
size = other_grid.size;
grid = new char *[other_grid.size];
for(int i = 0; i < size; i++) {
grid[i] = new char[size];
}
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
grid[i][j] = other_grid.grid[i][j];
}
}
}
析构
Grid::~Grid() {
for(int i = 0; i < size; i++) {
delete [] grid[i];
}
delete [] grid;
}
operator = overloading
Grid & Grid::operator=(Grid const &other_grid) {
size = other_grid.size;
grid = new char *[other_grid.size];
for(int i = 0; i < other_grid.size; i++) {
for(int j = 0; j < other_grid.size; j++) {
grid[i][j] = other_grid.grid[i][j];
}
}
return *this;
}
答案 0 :(得分:4)
不要浪费你的时间与那种手动分配疯狂。使用std::vector
。
class Grid {
Grid(unsigned int size);
private:
std::vector<std::vector<char>> grid;
};
Grid::Grid(unsigned int size)
: grid(size, std::vector<char>(size)) {}
你可以免费获得释放和工作副本(如果你使用现代编译器也可以移动)。
答案 1 :(得分:1)
编辑:更仔细地重新阅读您的代码。您的赋值运算符已损坏。您忘记在分配的网格中分配每一行。
单独一点:您不需要所有这些分配。你只需要一个。将grid
设为char*
而不是char**
并以此方式编写。我在这里省略了分配失败的检查。
Grid::Grid(unsigned int grid_size)
:size(grid_size), grid(0)
{
if (size > 0)
{
grid = new char[size*size];
}
}
Grid::Grid(Grid const &other_grid)
:size(0)
{
CopyFrom(other_grid);
}
Grid::~Grid()
{
if (size > 0)
{
delete [] grid;
grid = 0;
}
}
Grid& Grid::operator=(Grid const &other_grid)
{
CopyFrom(other_grid);
return *this;
}
void Grid::CopyFrom(Grid const &other_grid)
{
if (size > 0) delete [] grid;
size = newSize;
if (newSize > 0)
{
grid = new char[newSize*newSize];
memcpy(grid, other_grid.grid, newSize*newSize);
}
else
{
grid = 0;
}
}
然后,如果要在x,y点访问网格中的字节,可以这样写。 (我将给你留下适当的界限)。
char Grid::GetByte(int x, int y)
{
return grid[y*size + x];
}