Reputation: 575
How can I use std::shared_ptr for array of double? Additionally what are advantages/disadvantages of using shared_ptr.
Upvotes: 7
Views: 11756
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
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
Cons
Upvotes: 9