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

1
  • What about it doesn't work? How do you usually get values out of a smart pointer? Commented Dec 1, 2016 at 16:32

1 Answer 1

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[]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.