13

我不知道为什么这不起作用。以下Function是由placement new 创建的。提供了一个函数来检查它是否应该被破坏,如果是,则手动调用它的析构函数。

这是似乎从未调用析构函数的测试用例:

/* 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;
};

我像下面这样使用它。将下面的代码减少到仍然存在问题的最低限度。当然,在我的实际程序中,内存是从分配器以另一种方式分配的。

#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();
}

你可以看到我在 read 行中调用了析构函数~Function()。编译器接受,但最终并没有调用它:我通过检查它是否真的删除了我给它的 LLVM 代码来验证它(在删除指向的 LLVM 代码之前将一些代码放入析构函数中codeptr,以防万一Function有效的)。

后来我才知道是什么原因造成的。你能给我一个解释吗?

4

3 回答 3

24

这是因为~Function();这里在语法上不是析构函数调用。改为使用this->~Function();

~Function();被解析为操作符并在堆栈上~创建对象。类有一个,这就是为什么要编译它。FunctionFunctionoperator bool

于 2010-12-13T05:41:56.083 回答
8

将您的显式析构函数调用更改为

this->~Function();

目前 ~Function 正在构造一个“函数”,然后调用 ~ 位运算符,(合法,因为你有一个到 bool 的转换),然后破坏它,而不是被调用的对象。

于 2010-12-13T05:44:01.247 回答
-1

我记得不能明确调用析构函数。尝试将清理代码从析构函数移动到其他函数并调用它。

于 2010-12-13T05:30:44.883 回答