C++ – Usage of std::shared_ptr

c++shared-ptr

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

Best Solution

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)