I wanted to replace some raw pointers in my class with a std::shared_ptr
so that I don\'t have to worry when I create copies of that class. But the raw pointers
The solution you suggest is possible, but you will lose the size of the array:
#include
#include
using namespace std;
template shared_ptr make_shared_array(size_t size)
{
return shared_ptr(new T[size], default_delete());
}
struct Foo
{
shared_ptr field;
};
int main()
{
Foo a;
a.field = make_shared_array(256);
return 0;
}
What I have done here is to let the array decay into a pointer. As long as the deleter is an array deleter it should behave correctly.
To prevent this loss of size, and if you cannot use boost::shared_array as suggested, I would suggest to encapsulate this information in your own shared_array class.