以前,我有以下代码。

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

初始化a数组为0的目的是,当我迭代删除a元素时,即使仍然没有为a元素分配内存,一切仍然可以正常工作。
for (int i = 0; i < 100; i++) {
    // Fine.
    delete a[i];
}

现在,我想利用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);
}

我想知道,是否需要初始化auto_ptr来保存空指针?我的感觉不是。我只想确认一下,这样就不会有任何收获。

最佳答案

C++ 03指定auto_ptr的构造函数,如下所示:

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

Postconditions: *this holds the pointer p.

这意味着下面的内容格式正确。无需初始化
auto_ptr<int> a = auto_ptr<int>();

10-07 19:07
查看更多