How can I use std::shared_ptr for array of double? Additionally what are advantages/disadvantages of using shared_ptr.
Use shared_ptr if you want to share ownership of a resource. Many shared_ptr can point to a single resource. shared_ptr maintains reference count for this propose. when all shared_ptr's pointing to resource goes out of scope the resource is destroyed.
If your C++ implementation supports C++11 (or at least the C++11 shared_ptr ), then std::shared_ptr will be defined in <memory> . If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++).
shared_ptr is now part of the C++11 Standard, as std::shared_ptr . Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.
The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.
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
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 ());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With