Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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 there 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.

like image 699
Cheok Yan Cheng Avatar asked Jan 21 '26 01:01

Cheok Yan Cheng


1 Answers

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>();
like image 106
Chubsdad Avatar answered Jan 23 '26 17:01

Chubsdad