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;
};