我正在尝试声明一个动态 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
,但对于较大的类,您还可以使用唯一指针 vector 。
std::unique_ptr
是什么std::auto_ptr
想成为但由于语言的限制不能成为。
关于c++ - 如何使用 std::auto_ptr 声明动态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8320258/