C++ 是否需要将空指针指定给std::auto_ptr

C++ 是否需要将空指针指定给std::auto_ptr,c++,C++,在前面,我有以下代码 double* a[100]; for (int i = 0; i < 100; i++) { // Initialize. a[i] = 0; } 现在,我想利用auto_ptr,避免手动调用delete std::auto_ptr<double> a[100]; for (int i = 0; i < 100; i++) { // Initialize. Is there any need for me to do so

在前面,我有以下代码

double* a[100];
for (int i = 0; i < 100; i++) {
    // Initialize.
    a[i] = 0;
}
现在,我想利用auto_ptr,避免手动调用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);
}
std::auto_ptr a[100];
对于(int i=0;i<100;i++){
//初始化。我还需要这样做吗?
a[i]=std::auto_ptr(0);
}

我想知道,我是否需要初始化
auto_ptr
以保持空指针?我的感觉是否定的。我只是想确认一下,这样就不会有任何问题了。

您可以使用以下方法对数组的所有成员进行零初始化:

double* a[100] = {0}; // is equivalent
通过对每个使用
来替代删除:

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());
struct delete\u对象
{
模板
void运算符()(T*ptr){delete ptr;}
};
//在代码的后面。。。
std::对于_each(&a[0],&a[0]+sizeof a/sizeof a[0],删除_object());
现在回答你的问题:

我是否需要初始化auto_ptr以保持空指针

无需初始化
auto_ptr
s数组。如果不使用,则成员将默认初始化


但是,请注意,如果需要将指针传递给其他函数,则其移动语义(所有权副本)可能无法使用
auto_ptr
。此外,在即将推出的标准中,
auto_ptr
可能会被弃用。尝试使用类似于
std::tr1::unique_ptr
std::tr1::shared_ptr
(后者是一个引用计数的智能指针)。

std::auto_ptr
的默认构造函数为您执行空赋值,或者按照标准(ISO/IEC 14882:1998)的说法,构造函数声明为:

显式自动_ptr(X*p=0)throw()


X
是模板参数类,即这是用于
std::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>();
auto_ptr a=auto_ptr();

也许您可以解释为什么您认为首先需要一个指针数组加倍。将其更改为一个数组
auto_ptr
,在我看来,它似乎忽略了真正的问题。
auto_ptr<int> a = auto_ptr<int>();