是否有任何需要分配空指针到std :: auto_ptr [英] Is there any need to assign null pointer to std::auto_ptr

查看:133
本文介绍了是否有任何需要分配空指针到std :: auto_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上一页,我有以下代码。

Previous, I have the following code.

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

初始化 a 到0是,当我迭代删除 a 的元素,一切都会正常工作,即使没有分配内存仍然为 a

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];
}



现在,我想利用auto_ptr,避免手动调用

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);
}



我想知道,是否有任何需要我初始化 auto_ptr 来保存一个空指针?我的感觉是没有。

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.

推荐答案

C ++ 03指定了auto_ptr的构造函数如下:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆