4

我正在尝试声明一个动态int数组,如下所示:

int n;
int *pInt = new int[n];

我可以这样做std::auto_ptr吗?

我试过类似的东西:

std::auto_ptr<int> pInt(new int[n]);

但它不编译。

我想知道我是否可以用auto_ptr构造声明一个动态数组以及如何声明。谢谢!

4

2 回答 2

8

不,你不能,也不会: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_ptrstd::auto_ptr想要的,但由于语言的限制而不能。

于 2011-11-30T02:03:08.360 回答
0

你不能。std::auto_ptr无法处理动态数组,因为重新分配不同(deletevs delete[])。

但我想知道编译错误可能是什么......

于 2011-11-30T02:03:39.067 回答