标签:c c11 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];
但不断收到错误,说没有operator =匹配这些操作数.我在这做错了什么?
解决方法:
您不能将int *分配给std :: unique_ptr< int []>,这是导致错误的原因.正确的代码是
a[i] = std::unique_ptr<int[]>(new int[2]);
但是,piokuc是正确的,对于数组使用unique_ptr是非常不寻常的,因为这是std :: vector和std :: array的用途,具体取决于是否提前知道大小.
//make a 5x2 dynamic jagged array, 100% resizable any time
std::vector<std::vector<int>> container1(5, std::vector<int>(2));
//make a 5x2 dynamic rectangular array, can resize the 5 but not the 2
std::vector<std::array<2, int>> container1(5);
//make a 5x2 automatic array, can't resize the 2 or 5 but is _really fast_.
std::array<5, std::array<2, int>> container;
所有这些都可以初始化并使用与您已有的代码相同,除非它们更容易构建,并且您不必销毁它们.
标签:c,c11,unique-ptr 来源: https://codeday.me/bug/20191005/1855386.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。