c++arraysauto-ptr

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!


Solution

  • 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:

    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.