【发布时间】:2019-08-28 22:11:11
【问题描述】:
我想确定一个规范的方法来分配一个指针数组的等价物指向 int 的指针(如:int ** int_array),但使用 unique_ptr。
如果可能的话,我想要一个 C++11 解决方案,它可以扩展为指向类实例的指针的指针数组(我在这里使用整数来简化,我意识到当使用类实例)。
我了解如何创建一个固定大小的 unique_ptr 数组,其中大小是预先知道的。目标是在数组大小未知的情况下做同样的事情。
我看过一些相关的解决方案,包括下面的一个,但它们似乎只处理 unique_ptr 数组的固定分配(即,unique_ptr 数组的大小是预先知道的):
Proper way to create unique_ptr that holds an allocated array
我实现了一个简单的程序,试图演示和比较 3 种方法:指针的传统动态创建、unique_ptr 的固定数组和目标:unique_ptr 的动态数组。
#include <iostream> // include iostream
#include <memory> // include memory
using namespace std;
int main() {
cout << "Testing dynamic arrays of pointers\n";
int **num_array; // typical dynamic array of pointers to int
int count; // count of ints the user wants to generate
unique_ptr<int[]> f_num_array(new int[200]());
// above: fixed array of unique pointers to int - not what I want
unique_ptr<int[]> u_num_array;
// above: GOAL: dynamic array of unique pointers to int
int sum, u_sum, f_sum;
// above: test sum of each type of array (should match user count)
cout << "How many pointers would you like? ";
cin >> count; // get user input
num_array = new int*[count]; // allocate array of pointers on heap
//u_num_array = new int[count](); // GOAL - would like to do this
// above: ERROR: no overload for =; cannot allocate this way
for(int i=0; i<count; i++) { // allocate ints and store pointer
num_array[i] = new int(1); // pointer to an int on the heap
f_num_array[i] = 1; // assign 1 to the pre-allocated unique pointer array
unique_ptr<int> u_tmp(new int(1)); // temporary unique_ptr to int
// u_num_array[i] = u_tmp; // GOAL - would like to do this...
// ERROR: cannot assign unique_ptr this way
}
sum = 0; f_sum = 0; u_sum = 0; // init our sums to verify
for(int i=0; i<count; i++){
sum += *(num_array[i]); // summing our traditional array of pointers
f_sum += f_num_array[i]; // summing our fixed unique array of pointers
}
cout << "Sum = " << sum << "\n";
cout << "Sum (fixed unique_ptr array) = " << f_sum << "\n";
cout << "Sum (dynamic unique_ptr array) = " << u_sum << "\n";
delete[] num_array; // delete the dynamic array
f_num_array.release(); // delete the dynamic array
cout << "\nDone!\n";
}
【问题讨论】:
-
使用
std::vector,忘记new[]和delete[] -
唯一指针向量有什么问题?
-
#include <iostream> // include iostream是寄生评论的一个很好的例子:它已经说:#include <iostream>,为什么还要重复它? -
关于
using namespace std: stackoverflow.com/questions/1452721/…
标签: c++ c++11 dynamic-memory-allocation unique-ptr dynamic-arrays