Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::unique_ptr<void> with a custom deleter as a smart void*

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;
};
like image 724
steve9164 Avatar asked Mar 13 '13 12:03

steve9164


1 Answers

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.

like image 140
Ed Rowlett-Barbu Avatar answered Oct 20 '22 06:10

Ed Rowlett-Barbu