我有一个由指向指针的指针分配的double数组。使用std :: unique_ptr的双(二维)数组
// pointer to pointer
int **x = new int *[5]; // allocation
for (i=0; i<5; i++){
x[i] = new int[2];
}
for (i=0; i<5; i++){ // assignment
for (j=0; j<2; j++){
x[i][j] = i+j;
}
}
for (i=0; i<5; i++) // deallocation
delete x[i];
delete x;
我试图做到这一点使用unique_ptr
:
std::unique_ptr<std::unique_ptr<int>[]> a(new std::unique_ptr<int>[5]);
for (i=0; i<5; i++)
a[i] = new int[2];
,但一直得到一个错误,指出no operator = matches these operands
。我在这里做错了什么?
谢谢您的输入。我理解unique_ptr的方式是确保它指向的实例只有1个引用。所以使用unique_ptr指向一个unique_ptr来创建一个矩阵应该可以使用unique_ptr,因为不会有对该实例的另一个引用。另外,我不明白最后一句话背后的原因。谢谢。 – Evan 2012-03-21 14:15:02
任何RAII类应提供相同的独特保证。大多数C++类都是RAII。所以你应该使用正确的工具来完成这项工作。 vector和array应该优先于unique_ptr。 – 2012-03-21 15:14:04
唯一ptrs的原因主要是保存动态分配的单个对象。我不能马上想到在unique_ptr中存储数组的原因。 – 2012-03-21 15:16:16