我正在尝试声明一个动态int
数组,如下所示:
int n;
int *pInt = new int[n];
我可以这样做std::auto_ptr
吗?
我试过类似的东西:
std::auto_ptr<int> pInt(new int[n]);
但它不编译。
我想知道我是否可以用auto_ptr
构造声明一个动态数组以及如何声明。谢谢!
不,你不能,也不会:C++98 在数组方面非常有限,而且auto_ptr
是一个非常笨拙的野兽,通常不能满足你的需要。
你可以:
使用std::vector<int>
/ std::deque<int>
, 或std::array<int, 10>
, 或
使用 C++11 和std::unique_ptr<int[]> p(new int[15])
, 或
使用 C++11 和std::vector<std::unique_ptr<int>>
(虽然这感觉太复杂了int
)。
如果在编译时知道数组的大小,请使用其中一个静态容器(array
或数组唯一指针)。如果您必须在运行时修改大小,基本上使用vector
,但对于较大的类,您也可以使用唯一指针向量。
std::unique_ptr
是std::auto_ptr
想要的,但由于语言的限制而不能。
你不能。std::auto_ptr
无法处理动态数组,因为重新分配不同(delete
vs delete[]
)。
但我想知道编译错误可能是什么......