【问题标题】:How to create a matrix of pointers using smart pointers for a class?如何使用类的智能指针创建指针矩阵?
【发布时间】:2020-12-28 14:41:44
【问题描述】:

假设我们有以下 c 风格的代码

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

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

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

您将如何使用智能指针以 cpp 样式编写它?下面的可以吗?

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();

}

甚至可能是这样的:

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();

}

我怎样才能以最优雅和最节省内存的方式做到这一点?

【问题讨论】:

  • 这是c++,而不是c
  • 在 C++ 中你应该做 std::vector<:vector>>>
  • > how can I do it in the most elegant and memory-efficient way? 您的实际用例可能会有所不同,但从您向我们展示的情况来看,您所拥有的一切都很好。如“将工作”。 “优雅”是相当主观的,但是,如果您提前知道边界,您可能更喜欢 std::array 而不是 c 样式的数组。

标签: c++ class smart-pointers


【解决方案1】:

如果尺寸是固定的,我认为是固定的,那么您可以使用std::array。然后循环并用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多