0

How can I create a smart pointer to an array of double. I want to convert this expression :

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

using smart pointer auto_ptr

the following instruction doesn't work:

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

Also how to get the values of the array using the smart pointer.

Thanks

Younès

Quentin
  • 58,778
  • 7
  • 120
  • 175
Younès Raoui
  • 191
  • 1
  • 10

1 Answers1

1

You can't do this with std::auto_ptr, as auto_ptr does not contain a specialization for array*

Although auto_ptr doesn't allow this, you can use std::tr1::shared_ptr for a smart pointer array:

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

This will compile, but shared_ptr will incorrectly call delete (instead of delete[]) on your array which is undesirable, so you will need to provide a custom deleter.

The answer here provides the code that you will need (copied verbatim), although the answer is for 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>() );

Which for you, means you will need:

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

To access the elements in your smart pointer array, you will first need to use 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;
}

* Although your question is about C++03, it's worth noting that std::unique_ptr does contain partial specialization for an array, allowing this:

std::unique_ptr<double[]> d(new double[10]); // this will correctly call delete[]
Community
  • 1
  • 1
Tas
  • 6,589
  • 3
  • 31
  • 47