unique_ptr<int> ptr1(new int {});
unique_ptr<int[]> ptr2(new int[5] {});
单个和一维数组可以如上所述声明。如何将二维或更多数组声明为智能指针?
const size_t idx = 5;
// 2D
int** ptr3 = new int*[idx]{};
for (size_t i = 0; i < idx; i++)
{
ptr3[i] = new int[idx]{};
}
for (size_t i = 0; i < idx; i++)
{
delete[] ptr3[i];
}
delete[] ptr3;
// 3D
int*** ptr4 = new int**[idx]{};
for (size_t i = 0; i < idx; i++)
{
ptr4[i] = new int*[idx]{};
for (size_t j = 0; j < idx; j++)
{
ptr4[i][j] = new int[idx]{};
}
}
... skip ...
-----> smart pointer version?
答案 0 :(得分:0)
可能这是您正在寻找的但我不认为这是实用的。您可以使用矢量矢量或某种其他可以处理多维数组的结构或库。
int main()
{
unique_ptr<unique_ptr<int[]>[]> ptr(new unique_ptr<int[]>[5] {});
for (int i = 0; i < 5; i++)
{
unique_ptr<int[]> temp_ptr(new int[5]);
for (int j = 0; j < 5; j++)
temp_ptr[j] = i*5 + j;
ptr[i] = move(temp_ptr);
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
cout << ptr[i][j] << " ";
cout << "\n";
}
}