Using std :: shared_ptr

How can I use std :: shared_ptr for a double array? Also, what are the advantages / disadvantages of using shared_ptr.

+5
source share
2 answers

It depends on what you need. If you just want to resize the doubling array, go to

std::vector<double>

Example:

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

If you share ownership of the array, use, for example,

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

Regarding several advantages / disadvantages of shared_ptr go:

Arguments

  • - , , ,

  • , ( )
+9

deleter:

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

int main ()
{
    std::shared_ptr array (new double [256], ArrayDeleter ());
}
+6

All Articles