开发者

Is there any need to assign null pointer to std::auto_ptr

Previous, I have the following code.

double* a[100];
for (int i = 0; i < 100; i++) {
    // Initialize.
    a[i] = 0;
}

The purpose of initialize array of a to 0 is that, when I iterative delete element of a, everything will work fine still even there are no memory allocated still for element of a.

for (int i = 0; i < 100; i++) {
    // Fine.
    delete a[i];
}

Now, I would like to take advantage of auto_ptr, to avoid having manual call to delete.

std::auto_ptr<double> a[100];
for (int i = 0; i < 100; i++) {
    // Initialize. Is th开发者_开发百科ere any need for me to do so still?
    a[i] = std::auto_ptr<double>(0);
}

I was wondering, whether there is any need for me to initialize auto_ptr to hold a null pointer? My feeling is no. I just want to confirm on this, so that there aren't any catch behind.


The C++03 specifies the constructor of auto_ptr as follows:

explicit auto_ptr(X* p =0) throw();             // Note the default argument

Postconditions: *this holds the pointer p.

This means that the below is perfectly well-formed. There is no need to initialize

auto_ptr<int> a = auto_ptr<int>();


std::auto_ptr's default constructor does the NULL-assignment for you -- or, as the standard (ISO/IEC 14882:1998) puts it, the constructor is declared as:

explicit auto_ptr(X* p =0) throw();

(X being the template parameter class, i.e., this is for std::auto_ptr<X>).


You can zero initialize all members of an array using:

double* a[100] = {0}; // is equivalent

An alternative to deletion by using for_each:

struct delete_object
{
  template <typename T>
  void operator()(T *ptr){ delete ptr;}
};

//later in the code...
std::for_each( &a[ 0 ], &a[ 0 ] + sizeof a / sizeof a[ 0 ], delete_object());

Now for your question:

whether there is any need for me to initialize auto_ptr to hold a null pointer?

There is no need to initialize the auto_ptrs array. The members will be default initialized if you leave it out.

However, note that auto_ptr may not be usable for its move semantics (copy of ownership) if you need to pass around the pointers to other functions. Also, in the coming standard auto_ptr is likely to be deprecated. Try using something like std::tr1::unique_ptr or std::tr1::shared_ptr (the latter is a reference counted smart pointer).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜