全局运算符删除 - 语法

发布于 2024-10-21 01:08:40 字数 452 浏览 1 评论 0原文

我继承了一个不可更改的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三生池水覆流年 2024-10-28 01:08:40

嗯,看起来像是一个大锤方法,如果您只是这个结构的用户,并且担心它的内存管理方面,但又无法修改它,为什么不将它包装在代码中呢?

IE

class Sane_T
{
  public:
   Sane_T() 
   { 
     // do stuff 
   } 

   ~Sane_T()
   {
     // Now cleanup..
     if (_inst.val)
       free(_inst.val);
   }

  private:
    T _inst;
};

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;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文