I have a container class which receives a pointer to a dynamic array from a c api. This class then becomes the owner of the buffer and must delete it using delete[].
So this buffer might have been created as follows:
Value*ptr = malloc(10 * sizeof(Value));
I also have a class called ValueWrapper which operates on a single Value.
My container has a getter which returns ValueWrapper objects, something like this:
ValueWrapper Container::valueWrapper(int index)
{
return ValueWrapper(_value[index]);
}
However, objects of type VWrapper will have an invalid Value* once my container is destroyed.
How can I deal with this problem? I need to share ownership of Value*’s in some way. Would it be reasonable to insist that ValueWrapper objects can only be used when the Container is in scope and write this in the comment for Container::valueWrapper(int index)?
If you want shared ownership, then you can unpack the array into an array of std::shared_ptr and remove the deletions. If you don’t have C++11 support you could use
boost::shared_ptrorstd::tr1::shared_ptr.