在销毁对象放置后没有调用析构函数 - new'ed

Joh*_*itb 13 c++ destructor placement-new

我不知道为什么这不起作用.以下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;
};
Run Code Online (Sandbox Code Playgroud)

我用这个如下.将下面的代码减少到仍然存在问题的最小值.当然,在我的真实程序中,内存是从分配器以另一种方式分配的.

#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();
}
Run Code Online (Sandbox Code Playgroud)

你可以看到我在行阅读中调用析构函数~Function().编译器接受,但它并没有最终调用它:我验证它通过检查其是否真的删除LLVM代码,我把它(把一些代码放入析构函数删除LLVM代码的前codeptr点,万一Function是有效).

我后来发现了导致这种情况的原因.你能帮我解释一下吗?

Kir*_*sky 24

这是因为~Function();在这里没有语法上的析构函数调用.请this->~Function();改用.

~Function();被解析为运算符~Function在堆栈上创建对象.Functionclass有operator bool这就是为什么要编译它.

  • 但如果不是,如果你必须编写`Function :: ~Function()`,那么,什么是``Function()`解析为?将按位否定应用于临时的`Function`对象?我认为这不应该编译.OH UPDATE:他有一个隐含的转换为`bool`.JOHANNES,不要那样做! (6认同)
  • @Kirill V. Lyadvinsky:+1为好的解释,因为它为什么被编译,以及如何调用析构函数. (2认同)
  • 天啊.美好的一天!我刚刚学到了一些关于C++的新知识! (2认同)

Kei*_*ith 8

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

this->~Function();
Run Code Online (Sandbox Code Playgroud)

目前〜函数正在构造一个"函数",然后调用〜按位运算符(合法,因为你转换为bool),然后破坏它,而不是被调用的对象.