Global operator delete - grammar
I have inherited an unchangeable C struct that contains pointers to (alloc'd) memory.
typed开发者_如何学Cef struct {
int id;
int * val;
} T;
I would like to use new and delete on these objects, and I was wondering if it was possible to overload delete at global scope. I don't have the option of rewriting the struct / class in the first place. The trouble is I cannot find the correct grammar. This is what I have - it compiles but obviously fails since the function is applied to all delete calls:
void operator delete(void*p) throw() {
T * t = reinterpret_cast<T*>(p);
free(p->val);
}
Am I attempting the impossible? I have read that the operator delete overload does not have to be a member function, but does that just provide a means to write a generic delete for all pointers?
Hmm, seems like a sledgehammer approach, if you are simply a user of this structure, and worried about the memory management aspect of it, and yet cannot modify it, why don't you wrap it in your code?
i.e.
class Sane_T
{
public:
Sane_T()
{
// do stuff
}
~Sane_T()
{
// Now cleanup..
if (_inst.val)
free(_inst.val);
}
private:
T _inst;
};
精彩评论