2012-09-11 2 views
1

이 내 코드입니다 :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() 전화가 오기 전에 메모리를 해제해야합니까?

+4

'std :: vector '에 값을 저장할 때'delete []'를 사용하는 이유는 무엇입니까? 빠르고, 단순하고, 엉망진창을 짓기가 더 어렵습니다. 실수 할 경우 합리적인 실수를 범하기 쉽습니다. 싫어하는게 뭐야? – Rook

+0

@andand 죄송합니다. 때로는 사람들이 사용하고있는 물건에 대해 저에게 묻기 때문에이 모든 관련 코드를 넣었습니다.이 경우 메모리를 해제하는 방법에 대해 알아야하며 구축함이 좋은 문제 일 수 있다고 생각했기 때문입니다. – FacundoGFlores

+0

@Rook 좋아, 나는 선형 컨테이너에 대해 읽을 것이다. 고맙습니다! – FacundoGFlores

답변

6

는 아니, 그건 정확하지 않은 : 물론

vectorA = new float[W_A * H_A]; // allocates memory 
vectorA = A.Get_Vector();  // allocated memory is leaked 
           // vectorA now points to memory owned by A 
delete [] vectorA;    // delete memory owned by A 

, 당신은 일반적으로 단지 std::vector<float>을 사용 C++로.

+0

질문에서 인용 된 코드는 실제로'vectorA = A.Get_Vector'라고 말하기 때문에 Get_Vector가 멤버 함수이므로 컴파일하지 않을 가능성이 높습니다. 나는 ... 'Get_Vector()'가 그 의도와 함께 의도 된 것일지도 모른다는 것에 동의한다. – twalberg

+0

@Henrik 나는 네가 옳다고 생각한다. 그래서 vectorA는 Get_Vector 함수에서 할당 된 메모리를 가리켜 야합니까? std :: vector 을 사용하면 메모리 할당과 메모리를 확보하는 것에 대해 걱정하지 않아도됩니까? – FacundoGFlores

+0

@facunvd 예, 대신 std :: vector를 사용하십시오. –

관련 문제