使用智能指针进行数组

时间:2016-12-01 16:24:38

标签: arrays smart-pointers c++03

如何创建指向double数组的智能指针。我想转换这个表达式:

double* darr = new double[N]; // Notice the square brackets

使用智能指针auto_ptr

以下说明不起作用:

auto_ptr<double[]> darrp(new double[N]);

还有如何使用智能指针获取数组的值。

由于

尤尼斯

1 个答案:

答案 0 :(得分:1)

您无法使用std::auto_ptr执行此操作,因为auto_ptr不包含数组的专业化*

虽然auto_ptr不允许这样做,但您可以将std::tr1::shared_ptr用于智能指针数组:

#include <tr1/memory>
std::tr1::shared_ptr<double[]> d(new double[10]);

This will compile,但shared_ptr会错误地在您的阵列上调用delete(而不是delete[]),这是不受欢迎的,因此您需要提供自定义删除工具。

The answer这里提供了您需要的代码(逐字复制),尽管答案是针对C ++ 11的:

template< typename T >
struct array_deleter
{
  void operator ()( T const * p)
  { 
    delete[] p; 
  }
};

std::shared_ptr<int> sp( new int[10], array_deleter<int>() );

对你来说,意味着你需要:

std::tr1::shared_ptr<double> d( new double[10], array_deleter<double>() );

要访问智能指针数组中的元素,首先需要使用get() to dereference the smart pointer to obtain the raw pointer

std::tr1::shared_ptr<double> d( new double[10], array_deleter<double>() );
for (size_t n = 0; n < 10; ++n)
{
    d.get()[n] = 0.2 * n;
    std::cout << d.get()[n] << std::endl;
}

*虽然你的问题是关于C ++ 03的,但值得注意的是std::unique_ptr does contain partial specialization for an array,允许这样:

std::unique_ptr<double[]> d(new double[10]); // this will correctly call delete[]