DaianaB
DaianaB

Reputation: 33

Declare bi-directional matrix using smart pointers in C++

I want to know how to declare a bi-directional array in C++ using smart pointers. I am able to manage it with raw pointers. The code is:

    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";
        }
  };

Upvotes: 2

Views: 1321

Answers (1)

max66
max66

Reputation: 66200

Should be something like

#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};
 }

This solution use std::make_unique that is available starting from C++14.

In C++11 the constructor should be written as

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

En passant, your current destructor is wrong deleting val; with

 delete []val;

you free only the memory allocated with

 val = new int* [size1];

You have to delete also the memory allocated with

 val[i] = new int[size1];

that is

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

 delete[] val;

Upvotes: 1

Related Questions