为动态二维数组创建正确的复制构造函数
当调用复制构造函数时,我的程序出现段错误。这就是我的 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;
}
符 = 重载
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;
}
My program is seg faulting when the copy constructor is invoked. This is what my constructor looks like for my Grid class:
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];
}
}
And, this is my copy constructor that is causing the problem:
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];
}
}
}
Destructor
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:更仔细地重新阅读您的代码。您的赋值运算符已损坏。您忘记分配要分配到的网格中的每一行。
单独的一点:您不需要所有这些分配。你只需要一个。将
grid
设为char*
而不是char**
并这样编写。我在这里省略了对分配失败的检查。那么如果你想访问网格中x,y点处的一个字节,可以这样写。 (我会将适当的边界检查留给您)。
EDIT: Re-read your code more carefully. Your assignment operator is broken. You're forgetting to allocate each row in the grid you're assigning to.
Separate point: You don't need all of those allocations. You only need one. Make
grid
achar*
instead ofchar**
and write it this way. I leave out checks for allocation failures here.Then if you want to access a byte in the grid at a point x, y, you can write it like this. (I'll leave appropriate bounds checking to you).
不要在这种疯狂的手动分配上浪费时间。使用
std::vector
。并且您可以免费获得释放和工作副本(如果您使用的是现代编译器,也可以移动)。
Don't waste your time with that kind of manual allocation madness. Use
std::vector
.And you get deallocation and working copies (and moves too, if you're using a modern compiler) for free.