I am trying to declare a dynamic int array like below:
int n;
int *pInt = new int[n];
Can I do this with std::auto_ptr?
I tried something like:
std::auto_ptr<int> pInt(new int[n]);
But it doesn’t compile.
I’m wondering if I could declare a dynamic array with auto_ptr construct and how. Thanks!
No, you cannot, and it will not: C++98 is very limited when it comes to arrays, and
auto_ptris a very awkward beast that often doesn’t do what you need.You can:
use
std::vector<int>/std::deque<int>, orstd::array<int, 10>, oruse C++11 and
std::unique_ptr<int[]> p(new int[15]), oruse C++11 and
std::vector<std::unique_ptr<int>>(though that feels too complicated forint).If the size of the array is known at compile time, use one of the static containers (
arrayor an array-unique-pointer). If you have to modify the size at runtime, basically usevector, but for larger classes you can also use a vector of unique-pointers.std::unique_ptris whatstd::auto_ptrwanted to be but couldn’t due to the limitations of the language.