【发布时间】: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