I need to write a function to retrieve and process some data. This data may be allocated in several ways (on the data segment, on the heap, on a shared memory segment and so on):
T *data;
if( global ) data = &d;
if( heap ) data = new T [ size ];
if( shm ) data = (T*) shmat( id, 0, 0 );
// processing data ...
Since data may be dynamically allocated, I'd think that the best way to handle it is using an unique_ptr or some other kind of smart pointers. However it's not always dynamically allocated: I'd need to choose at runtime the deleter for unique_ptr, but that's not possible.
How should I define and handle data?
You could make the custom deleter take a run-time value!
struct MyCustomDeleter
{
MemoryType type;
template <typename T>
void operator()(T* value) const
{
switch (type)
{
case MemoryType::heap:
delete[] value;
break;
case MemoryType::shm:
unmap_from_shm(value);
break;
// etc.
}
}
};
...
std::unique_ptr<T, MyCustomDeleter> ptr (new T[size],
MyCustomDeleter{MemoryType::heap});
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