问题描述
假设我们有以下 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();
}
我怎样才能以最优雅和最节省内存的方式做到这一点?
解决方法
如果尺寸是固定的,我认为它们是固定的,那么您可以使用 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;
}