I have a generic class myClass
that sometimes needs to store extra state information depending on the use. This is normally done with a void*
, but I was wondering if I could use a std::unique_ptr<void, void(*)(void*)>
so that the memory is released automatically when the class instance is destructed. The problem is that I then need a to use a custom deleter as deleting a void* results in undefined behaviour.
Is there a way to default construct a std::unique_ptr<void, void(*)(void*)>
, so that I don't have construct it first with a dummy deleter then set a real deleter when I use the void*
for a state struct? Or is there a better way to store state information in a class?
Here is some sample code:
void dummy_deleter(void*) { }
class myClass
{
public:
myClass() : m_extraData(nullptr, &dummy_deleter) { }
// Other functions and members
private:
std::unique_ptr<void, void(*)(void*)> m_extraData;
};
Probably a more intuitive way to store extra information would be to have an interface IAdditionalData with a virtual destructor.
Whatever data structures you may have would inherit from IAdditionalData and be stored in a std::unique_ptr<IAdditionalData>
.
This also provides a bit more type safety, as you would static cast between IAdditionalData and the actual type, instead of reinterpret_cast between void *
and whatever data type.
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