How to declare a dynamic array using std :: auto_ptr?

I am trying to declare a dynamic int array as shown 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 does not compile.

I am wondering if I can declare a dynamic array with the auto_ptr construct and how. Thanks!

+4
source share
2 answers

No, you can't, and it won't: C ++ 98 is very limited when it comes to arrays, and auto_ptr is a very uncomfortable 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>> (although this is too complicated for int ).

If the size of the array is known at compile time, use one of the static containers ( array or a unique pointer to an array). If you need to resize at runtime, mostly use vector , but for larger classes, you can also use a vector of unique pointers.

std::unique_ptr is what std::auto_ptr wanted, but could not because of language restrictions.

+7
source

You can not. std::auto_ptr cannot handle dynamic arrays, as the redistribution is different ( delete vs delete[] ).

But I wonder what compilation error might be ...

0
source

Source: https://habr.com/ru/post/1383780/


All Articles