2016-12-29 74 views
2

我想知道如何使用智能指針在C++中聲明雙向數組。我可以用原始指針來管理它。該代碼是:在C++中聲明使用智能指針的雙向矩陣

class Matrice{ 

    int size; 
    int **val; 

    public: 
     Matrice(int size1) 
     { 
      val = new int* [size1]; 
      size = size1; 
      for (int i = 0; i < size1; i++) 
      { 
       val[i] = new int[size1]; 
      } 

      for (int i = 0; i < size1; i++){ 
       for (int j = 0; j < size1; j++) 
       { 
        val[i][j] = j; 
       } 
      }  
     } 

     ~Matrice() 
     { 
      delete []val; 
      cout<<"Destroyed matrix! \n"; 
     } 
    }; 

回答

1

應該像

#include <memory> 
#include <iostream> 


class Matrice 
{ 
    int size; 

    std::unique_ptr<std::unique_ptr<int[]>[]> val; 

    public: 

    Matrice(int size1) : size{size1}, 
     val{ std::make_unique< std::unique_ptr<int[]>[] >(size) } 
    { 
     for (int i = 0; i < size; ++i) 
     { 
     val[i] = std::make_unique<int[]>(size); 

     for (int j = 0; j < size; ++j) 
      val[i][j] = j; 
     } 
    } 

    ~Matrice() 
    { std::cout << "Destroyed matrix! (no more delete[]) \n"; } 
}; 

int main() 
{ 
    Matrice m{12}; 
} 

該解決方案使用std::make_unique,可從C++ 14起。

在C++ 11的構造應寫爲

Matrice(int size1) : size{size1}, 
     val{ std::unique_ptr<std::unique_ptr<int[]>[]> 
      {new std::unique_ptr<int[]>[size]} } 
    { 
     for (int i = 0; i < size; ++i) 
     { 
     val[i] = std::unique_ptr<int[]>{ new int[size] }; 

     for (int j = 0; j < size; ++j) 
      val[i][j] = j; 
     } 
    } 

順便,你目前的析構函數是錯誤的刪除val;與

delete []val; 

您免費只有內存與

val = new int* [size1]; 

分配你必須還刪除與

val[i] = new int[size1]; 

分配的內存是

for (i = 0 ; i < size ; ++i) 
    delete[] val[i]; 

delete[] val; 
+0

確定。萬分感謝 – DaianaB