【问题标题】:Declare bi-directional matrix using smart pointers in C++在 C++ 中使用智能指针声明双向矩阵
【发布时间】:2016-12-29 11:14:05
【问题描述】:

我想知道如何使用智能指针在 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";
        }
  };

【问题讨论】:

    标签: c++ c++11 multidimensional-array smart-pointers


    【解决方案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};
     }
    

    此解决方案使用从 C++14 开始可用的 std::make_unique

    在 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;
    

    【讨论】:

    • 好的。非常感谢
    猜你喜欢
    • 2011-06-14
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2013-01-05
    • 2016-08-07
    • 2019-09-21
    • 1970-01-01
    相关资源
    最近更新 更多