简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM