全局运算符删除 - 语法
我继承了一个不可更改的 C 结构,其中包含指向(分配的)内存的指针。
typedef struct {
int id;
int * val;
} T;
我想在这些对象上使用 new 和 delete ,并且我想知道是否可以在全局范围内重载删除。我首先无法选择重写结构/类。问题是我找不到正确的语法。这就是我所拥有的 - 它可以编译,但显然会失败,因为该函数应用于所有删除调用:
void operator delete(void*p) throw() {
T * t = reinterpret_cast<T*>(p);
free(p->val);
}
我是否在尝试不可能的事情?我读过,运算符删除重载不一定是成员函数,但这是否只是提供了一种为所有指针编写通用删除的方法?
I have inherited an unchangeable C struct that contains pointers to (alloc'd) memory.
typedef 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,看起来像是一个大锤方法,如果您只是这个结构的用户,并且担心它的内存管理方面,但又无法修改它,为什么不将它包装在代码中呢?
IE
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.