我不知道为什么这不起作用。下列Function
是通过放置 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();
}
你可以看到我在行中调用析构函数~Function()
。编译器接受,但它最终不会调用它:我通过检查它是否真的删除了我给它的 LLVM 代码来验证它(在删除 LLVM 代码之前将一些代码放入析构函数中)codeptr
指向,如果Function
已验证)。
后来我才知道是什么原因造成的。您能给我一个解释吗?
这是因为~Function();
这里在语法上不是析构函数调用。使用this->~Function();
反而。
~Function();
被解析为运算符~
和创建Function
堆栈上的对象。Function
类有一个operator bool
这就是为什么要编译这个的原因。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)