析构函数在销毁对象放置之后不被调用 [英] Destructor not called after destroying object placement-new'ed

查看:194
本文介绍了析构函数在销毁对象放置之后不被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有线索为什么这不工作。以下函数是通过placement new创建的。提供了一个函数来检查它是否应该被销毁,如果是,则手动调用它的析构函数。

I had no clue why this doesn't work. The following Function is created by placement new. A function is provided that checks whether it should be destructed, and if so, calls its destructor manually.

这里是一个测试用例,似乎析构函数从未被调用:

Here is the testcase where it seems the destructor is never called:

/* Represents a function at runtime */ 
class Function {
public:
  /* Creates an invalid function */
  Function():codeptr(0) { }

  /* Creates a function with the given code pointer */
  Function(void *codeptr):codeptr(codeptr) { }

  /* Frees the function machine code */
  ~Function() {
    if(*this) {
      /* <- I explicitly put a debug output here! */
      destroyLLVMCode(codeptr);
    }
  }

public:
  /* Returns true if the function is valid 
   * (if the code pointer is non-null)
   */
  operator bool() const { return codeptr != 0; }

  /* Destroy this function by calling its destructor */
  void destroy() { ~Function(); }

private:
  void *codeptr;
};

我使用这个像下面这样。将下面的代码降低到仍然显示问题的最小值。在我真正的程序中,当然,内存以另一种方式,从分配器分配。

I used this like the following. Cut down the code below to the minimum that still exhibits the problem. In my real program, of course, the memory is allocated in another manner, from an allocator.

#include <new>
#include <cstdlib>

int main() { 
  void *buffer = std::malloc(sizeof(Function));
  Function *f = new (buffer) Function(someExecutableLLVMCode);
  /* more code .. register with symbol tables etc.. */
  f->destroy();
}

你可以看到我正在调用析构函数〜Function()。编译器接受,但它不会结束调用它:我验证它通过检查它是否真的删除我给它的LLVM代码(在删除LLVM代码之前,将一些代码放入析构函数 codeptr 指向,以便 Function 有效)。

You can see I'm calling the destructor in the line reading ~Function(). The compiler accepts, but it doesn't end up calling it: I verified it by checking whether it really deletes the LLVM code I gave it (put some code into the destructor before deleting the LLVM code that the codeptr points to, in case the Function is valid).

我发现后来导致的是什么。 c>〜Function();

I found out later on what is causing that. Could you please provide me with an explanation?

推荐答案

code> in语法不是析构函数。

This is because ~Function(); in not a destructor call syntactically here. Use this->~Function(); instead.

〜Function() this-> ; 被解析为操作符并在堆栈上创建 Function 对象。 函数类具有运算符bool ,这就是为什么这将被编译。

~Function(); is parsed as an operator ~ and creation of the Function object on the stack. Function class has an operator bool that's why this will be compiled.

这篇关于析构函数在销毁对象放置之后不被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆