이 내 코드입니다 :delete [] 연산자를 올바르게 사용하고 있습니까?
linearMatrix lAmatrixmatrixmult(const linearMatrix &A,
const linearMatrix &B)
{
//Local variables
int W_A = A.Get_Width;
int H_A = A.Get_Height;
int H_B = B.Get_Height;
int W_B = B.Get_Width;
float *vectorA;
float *vectorB;
float *vectorC;
//================
//Memory allocation
try{
vectorA = new float[W_A * H_A];
}
catch(bad_alloc &ex)
{
cerr << "Exception:" << ex.what();
exit(1);
}
try{
vectorB = new float[W_B * H_B];
}
catch(bad_alloc &ex)
{
cerr << "Exception:" << ex.what();
exit(1);
}
try{
vectorC = new float[W_A * H_B];
}
catch(bad_alloc &ex)
{
cerr << "Exception:" << ex.what();
exit(1);
}
//=================
//Initialization
vectorA = A.Get_Vector;
vectorB = B.Get_Vector;
//==============
if(W_A == H_B)
{
linearMatrix C(W_A, H_B);
for(int i = 0; i < W_A; i++)
{
for(int j = 0; j < W_B; j++)
{
float sum = 0;
for(int k = 0; k < W_A; k++)
{
float a = vectorA[i * W_A + k];
float b = vectorB[k * H_B + j];
sum += a * b;
}
vectorC[i * W_A + j] = sum;
}
}
C.Set_Vector(vectorC, W_A, H_B);
//Free memory
delete [] vectorA;
delete [] vectorB;
delete [] vectorC;
//===========
return C;
}
else
{
cout << "Different sizes! Cannot perform mmmult" << endl;
//Free memory
delete [] vectorA;
delete [] vectorB;
delete [] vectorC;
//===========
exit(1);
}
}
그리고 ~linearMatrix
은 다음과 같습니다 linearMatrix
는
//Destructor definition
linearMatrix::~linearMatrix()
{
delete [] myVector;
}
:
class linearMatrix
{
public:
//Constructor
linearMatrix(const int Width, const int Heigth);
//Copy constructor
linearMatrix(const linearMatrix &that);
//Copy assignment operator
linearMatrix& operator=(const linearMatrix& that);
//Destroyer
~linearMatrix();
//We read a matrix file
void Read_File_Matrix(const char *Path);
//We write a matrix file
void Write_File_Matrix(const char *Path);
//Generate a diagonal dominant matrix
void Generate_Diagonal_Dominant(void);
//Generate a random matrix
void Generate_Random_Matrix(void);
//Set a float *vector
void Set_Vector(const float *V, const int Width, const int Heigth);
//Show a little vector
void Show_Little_Matrix(void);
//Get the vector
//Suppose V is previously allocated
float *Get_Vector(void);
//Get total number of elements
int Get_NumberofElements(void);
//Get Width
int Get_Width(void);
//Get Height
int Get_Height(void);
private:
int myWidth, myHeight; // Width and Height
float* myVector;
//Aux function for testing
bool Test_Sizes(const int Width, const int Heigth);
};
머스트 나는 내가 new
을 사용하면 함수를 떠나기 전에 사용 가능한 메모리 함수 내부의 연산자? 어떤 exit()
전화가 오기 전에 메모리를 해제해야합니까?
'std :: vector'에 값을 저장할 때'delete []'를 사용하는 이유는 무엇입니까? 빠르고, 단순하고, 엉망진창을 짓기가 더 어렵습니다. 실수 할 경우 합리적인 실수를 범하기 쉽습니다. 싫어하는게 뭐야? –
Rook
@andand 죄송합니다. 때로는 사람들이 사용하고있는 물건에 대해 저에게 묻기 때문에이 모든 관련 코드를 넣었습니다.이 경우 메모리를 해제하는 방법에 대해 알아야하며 구축함이 좋은 문제 일 수 있다고 생각했기 때문입니다. – FacundoGFlores
@Rook 좋아, 나는 선형 컨테이너에 대해 읽을 것이다. 고맙습니다! – FacundoGFlores