ido_asks17
ido_asks17

Reputation: 1

How to create a matrix of pointers using smart pointers for a class?

Let's say we have the following code in c-style

class Dog {
public:
    void woof() {};
};

int main() {
    Dog* mat[5][5];

    mat[0][0] = new Dog();
    
    mat[0][0]->woof();
}

How would you write it in cpp style using smart pointers? is the following is fine?

class Dog {
public:
    void woof() {};
};

int main() {
    std::unique_ptr<Dog> mat[5][5];

    mat[0][0] = std::make_unique<Dog>();
    
    mat[0][0]->woof();

}

or maybe even something such as:

class Dog {
public:
    void woof() {};
};

int main() {
    std::unique_ptr<std::unique_ptr<std::unique_ptr<Dog>[]>[]> mat = std::make_unique<std::unique_ptr<std::unique_ptr<Dog>[]>[]>(5);
    for (int i = 0; i < 5; i++)
        mat[i] = std::make_unique<std::unique_ptr<Dog>[]>(5);

    mat[0][0] = std::make_unique<Dog>();
    
    mat[0][0]->woof();

}

how can I do it in the most elegant and memory-efficient way?

Upvotes: 0

Views: 85

Answers (1)

jignatius
jignatius

Reputation: 6484

If the dimensions are fixed, which I think they are, then you can use std::array. Then loop through and fill the elements with std::generate:

#include <iostream>
#include <array>
#include <algorithm>
#include <memory>

class Dog {
public:
    void woof() { std::cout << "woof" << std::endl; };
};


int main() {
    std::array<std::array<std::unique_ptr<Dog>, 5>, 5> matrix;

    for (int x=0; x < 5; ++x)
    {
        std::generate(std::begin(matrix[x]), std::end(matrix[x]), 
            []{ return std::make_unique<Dog>(); } );
    }

    matrix[0][0]->woof();
    matrix[4][4]->woof();
    
    return 0;
}

Demo

Upvotes: 1

Related Questions