7

How can I use std::shared_ptr for array of double? Additionally what are advantages/disadvantages of using shared_ptr.

arbitUser1401
  • 575
  • 2
  • 8
  • 25
  • 1
    You don't use `std::shared_ptr` for a dynamically allocated array, it doesn't call the proper `delete`. You probably want `std::vector`. – wkl Mar 26 '12 at 16:52
  • 1
    @birryree: Technically speaking, you could go for a std::shared_ptr> if the shared ownership semantics were important to you. Or Boost's shared_array. See this question for example: http://stackoverflow.com/questions/6796655/why-use-one-vs-the-other-boostshared-array-vs-boostshared-ptrstdvecto – Stuart Golodetz Mar 26 '12 at 16:56
  • 3
    @StuartGolodetz - good point about the ownership semantics. piyush314 would have to know that `shared_array` is a Boost construct (not standard), and if he really, really wanted a raw allocated array, he could use a `std::default_delete` argument for the pointer deleter, like this: `std::shared_ptr name(new double[size], std::default_delete());`. – wkl Mar 26 '12 at 16:59
  • Indeed - I was just adding 'Boost's' there while you were writing that :) – Stuart Golodetz Mar 26 '12 at 17:01

2 Answers2

9

It depends on what you're after. If you just want a resizable array of doubles, go with

std::vector<double>

Example:

std::vector<double> v;
v.push_back(23.0);
std::cout << v[0];

If sharing the ownership of said array matters to you, use e.g.

std::shared_ptr<std::vector<double>>

Example:

std::shared_ptr<std::vector<double>> v1(new std::vector<double>);
v1->push_back(23.0);
std::shared_ptr<std::vector<double>> v2 = v1;
v2->push_back(9.0);
std::cout << (*v1)[1];

Alternatively, Boost has

boost::shared_array

which serves a similar purpose. See here:

http://www.boost.org/libs/smart_ptr/shared_array.htm

As far as a few advantages/disadvantages of shared_ptr go:

Pros

  • Automated shared resource deallocation based on reference counting - helps avoid memory leaks and other problems associated with things not getting deallocated when they should be
  • Can make it easier to write exception-safe code

Cons

  • Memory overhead to store the reference count can be significant for small objects
  • Performance can be worse than for raw pointers (but measure this)
Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
5

You can also provide an array deleter:

template class ArrayDeleter {
public:
    void operator () (T* d) const
    { delete [] d; }
};

int main ()
{
    std::shared_ptr array (new double [256], ArrayDeleter ());
}
perreal
  • 94,503
  • 21
  • 155
  • 181
  • 1
    You could also just use a lambda, I think: `std::shared_ptr array(new double[256], [](double *d) { delete [] d; } );`. – Frerich Raabe Jul 19 '13 at 22:10