gpt4 book ai didi

c++ - 动态 3d 数组的声明和分配

转载 作者:行者123 更新时间:2023-11-30 02:01:08 24 4
gpt4 key购买 nike

我已经为 3d 数组创建了下一个类。声明一个变量,例如

Grid3d n = Grid3d(2,2,2);
n(0,0,0) = 1;

工作正常,但声明为

Grid3d n;
n = Grid3d(2,2,2);
n(0,0,0) = 1;

给我一​​个段错误,问题似乎是默认构造函数,但我不知道如何修复它,有什么线索吗?

#ifndef _GRID3D_
#define _GRID3D_

#include <iostream>
#include <cmath>
#include <cassert> // assert()

using namespace std;

class Grid3d
{
private:
int L;
int M;
int N;
double *** G;

public:
Grid3d(int,int,int);
Grid3d();
Grid3d(const Grid3d &);
~Grid3d();

double & operator()(int,int,int);
};
#endif

//Constructor
Grid3d::Grid3d(int L,int M,int N)
:L(L), M(M), N(N)
{
int i,j,k;
G = new double ** [L];
for (i=0;i<L;i++){
G[i] = new double * [M];
for (j=0;j<M;j++){
G[i][j] = new double [N];
for (k=0;k<N;k++){
G[i][j][k] = 0;
}
}
}
}

//Constructor vacío
Grid3d::Grid3d()
:L(0), M(0), N(0)
{
G = NULL;
}

//Constructor copia
Grid3d::Grid3d(const Grid3d &A)
:L(A.L), M(A.M), N(A.N)
{
G = new double ** [L];
int i,j,k;
for (i=0;i<L;i++){
G[i] = new double * [M];
for (j=0;j<M;i++){
G[i][j] = new double [N];
for (k=0;k<N;k++){
G[i][j][k] = A.G[i][j][k];
}
}
}
}

//Destructor
Grid3d::~Grid3d()
{
// Libera memoria
for (int i=0;i<L;i++){
for (int j=0;j<M;j++){
delete [] G[i][j];
G[i][j] = NULL;
}
delete [] G[i];
G[i] = NULL;
}
delete G;
G = NULL;
}

double& Grid3d::operator()(int i,int j,int k)
{
assert(i >= 0 && i < L);
assert(j >= 0 && j < M);
assert(k >= 0 && k < N);
return G[i][j][k];
}

赋值运算符

Grid3d Grid3d::operator = (const Grid3d &A)
{
if (this == &A) {return *this;};
if (G != NULL){
// Libera memoria
for (int i=0;i<L;i++){
for (int j=0;j<M;j++){
delete [] G[i][j];
G[i][j] = NULL;
}
delete [] G[i];
G[i] = NULL;
}
delete G;
G = NULL;
}

L = A.L;
M = A.M;
N = A.N;
G = new double ** [L];
int i,j,k;
for (i=0;i<L;i++){
G[i] = new double * [M];
for (j=0;j<M;i++){
G[i][j] = new double [N];
for (k=0;k<N;k++){
G[i][j][k] = A.G[i][j][k];
}
}
}
return *this;
}

最佳答案

你动态分配了内存,但是你没有遵循rule of three .您缺少赋值运算符,因此当您这样做时:

Grid3d n;
n = Grid3d(2,2,2); // both RHS temporary and n point to the same data.
n(0,0,0) = 1; // Accessing deleted memory: undefined behaviour.

你将有两次尝试取消分配同一内存,因为你有 n 的指针指向与第二行中用于分配给它的临时内存相同的内存。当临时死亡时,它会取消分配它的内存。当 n 死亡时,它会尝试释放相同的内存。此外,在第二行之后对该内存的任何访问都是未定义的行为。

关于c++ - 动态 3d 数组的声明和分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com