Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a dynamic array with std::auto_ptr?

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!

like image 777
itnovice Avatar asked Feb 22 '23 06:02

itnovice


1 Answers

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.

like image 168
Kerrek SB Avatar answered Mar 04 '23 04:03

Kerrek SB