It seems to me that auto_ptr can wrap up single pointer. How can I use it to wrap up an array of pointers? Please see the following example for my intention:
class Cat { ...};
void foo(int num){
{
Cat* p = new Cat[num]; // I want to use auto_ptr here instead
// do sth;
}
So my question is: how can I use auto_ptr for an array of pointers to Cat objects:
void foo(int num){
{
auto_ptr<Cat> p(new Cat[num]); // error: exception results when p is automatically deleted
// do sth;
}
Also, I am pretty sure auto_ptr only lets you point to one element...so you could try looking at boost's smart pointer and see if that works (I haven't checked).
Yes, I might use std::vector<Cat*>. However, for this I have to manually delete each pointer stored in the vector once they are no longer needed to avoid memory leak and track when I have to do so. I thought of std::vector< auto_prt<Cat> >, but it does not compile. If auto_ptr works for an array of pointers, that would save me a lot of headache of memory leak, resource cleaning when exceptions occur, etc.
I will take a look at boost's smart pointer. Thank firedraco for the suggestion.
Yes. Boost's smart pointer "scoped_array class template" is the solution as follows:
#include <boost/scoped_array.hpp>
void foo(int num){
{
boost::scoped_array<Cat> ptrcat( new Cat[num]);
// throw exception here // all newly allocated array of num Cats objects are destroyed automatically. NICE!
// do sth // this can never be done due to the exception above
}