arbitUser1401
arbitUser1401

Reputation: 575

Usage of std::shared_ptr

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

Upvotes: 7

Views: 11756

Answers (2)

perreal
perreal

Reputation: 98118

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 ());
}

Upvotes: 5

Stuart Golodetz
Stuart Golodetz

Reputation: 20656

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)

Upvotes: 9

Related Questions