c++ - Using std::unique_ptr<void> with a custom deleter as a smart void* -
i have generic class myclass needs store state information depending on use. done void*, wondering if use std::unique_ptr<void, void(*)(void*)> memory released automatically when class instance destructed. problem need use custom deleter deleting void* results in undefined behaviour.
is there way default construct std::unique_ptr<void, void(*)(void*)>, don't have construct first dummy deleter set real deleter when use void* state struct? or there better way store state information in class?
here sample code:
void dummy_deleter(void*) { } class myclass { public: myclass() : m_extradata(nullptr, &dummy_deleter) { } // other functions , members private: std::unique_ptr<void, void(*)(void*)> m_extradata; };
probably more intuitive way store information have interface iadditionaldata virtual destructor. whatever data structures may have inherit iadditionaldata , stored in std::unique_ptr<iadditionaldata>.
this provides bit more type safety, static cast between iadditionaldata , actual type, instead of reinterpret_cast between void * , whatever data type.
Comments
Post a Comment