itn*_*ice 4 c++ arrays auto-ptr
我试图声明一个动态int数组,如下所示:
int n;
int *pInt = new int[n];
Run Code Online (Sandbox Code Playgroud)
我可以这样做std::auto_ptr吗?
我尝试过类似的东西:
std::auto_ptr<int> pInt(new int[n]);
Run Code Online (Sandbox Code Playgroud)
但它没有编译.
我想知道我是否可以使用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想成为但不能由于语言的限制.