上一篇,我有以下代码.
double* a[100];
for (int i = 0; i < 100; i++) {
// Initialize.
a[i] = 0;
}
Run Code Online (Sandbox Code Playgroud)
初始化数组a为0 的目的是,当我迭代删除元素时a,一切都会正常工作,即使没有为元素分配的内存a.
for (int i = 0; i < 100; i++) {
// Fine.
delete a[i];
}
Run Code Online (Sandbox Code Playgroud)
现在,我想利用auto_ptr,以避免手动调用删除.
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);
}
Run Code Online (Sandbox Code Playgroud)
我想知道,是否需要初始化auto_ptr以保存空指针?我的感觉是否定的.我只是想确认这一点,以便没有任何陷阱.
std::auto_ptr默认构造函数为您执行NULL赋值 - 或者,正如标准(ISO/IEC 14882:1998)所述,构造函数声明为:
显式auto_ptr(X*p = 0)throw();
(X作为模板参数类,即,这是为了std::auto_ptr<X>).
C++ 03指定auto_ptr的构造函数如下:
explicit auto_ptr(X* p =0) throw(); // Note the default argument
Postconditions: *this holds the pointer p.
Run Code Online (Sandbox Code Playgroud)
这意味着下面是完美的形式.无需初始化
auto_ptr<int> a = auto_ptr<int>();
Run Code Online (Sandbox Code Playgroud)