I got a function pointer for a deleter, but most of the time, the deleter is not gonna be needed, only when I maintain an internal copy of something. Currently I do that with a noop deleter function:
class MyClass{
public:
// bind object
template<class Type>
void Bind(Type* obj){
Cleanup();
object_ = obj;
}
// bind object with internal copy
template<class Type>
void Bind(Type obj){
Cleanup();
object_ = new Type(obj);
deleter = &Deleter<Type>;
}
private:
template<class Type>
static void Deleter(void* obj_ptr){
Type* obj = static_cast<Type*>(obj_ptr);
delete obj;
}
static void NoopDeleter(void* unused){
}
void Cleanup(){
(*deleter_)(object_);
object_ = 0;
deleter_ = &NoopDeleter;
}
typedef void (*DeleterFunc)(void*);
void* object_;
DeleterFunc deleter_;
};
Now the obvious other choice would be to set it to 0
when not needed, and check in the Cleanup
function with if(deleter_ != 0) (*deleter_)(object_)
.
Now during the coding, it just came to my mind "Hm, which version would be faster?", so it's more of a personal interest rather than optimization. Sorry if the question sounds kinda stupid, but it kinda bugs me and I really want to know. Thanks for any answers in advance!