我不知道为什么这不起作用。以下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
有效的)。
后来我才知道是什么原因造成的。你能给我一个解释吗?