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_ptr is a very awkward beast that often doesn't do what you need.
You can:
use std::vector<int>/std::deque<int>, or std::array<int, 10>, or
use C++11 and std::unique_ptr<int[]> p(new int[15]), or
use C++11 and std::vector<std::unique_ptr<int>> (though that feels too complicated for int).
If the size of the array is known at compile time, use one of the static containers (array or an array-unique-pointer). If you have to modify the size at runtime, basically use vector, but for larger classes you can also use a vector of unique-pointers.
std::unique_ptr is what std::auto_ptr wanted to be but couldn't due to the limitations of the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With